1. 程式人生 > 其它 >React-Antd4的Form表單校驗

React-Antd4的Form表單校驗

之前很少用react做專案,最近入職新公司,用的react,在自己的摸索過程中,慢慢會記錄一些使用方法。今天簡單記錄一下使用antd 4.0版本的Form表單校驗,直接程式碼。

需要購買阿里雲產品和服務的,點選此連結領取優惠券紅包,優惠購買哦,領取後一個月內有效:https://promotion.aliyun.com/ntms/yunparter/invite.html?userCode=fp9ccf07

1、程式碼:

import React, {Component} from 'react'
import { Form, Input, Row, Col, Select, Button } from 
'antd' class FormDemo extends Component { constructor(props){ super(props) } formRef = React.createRef() componentDidMount(){ const leftMenu = document.getElementById('left_menu') leftMenu.style.minWidth = '0px' leftMenu.style.maxWidth = '0px' } submit =()=>{  // 點選提交時,做最後的校驗
const form
= this.formRef.current form.validateFields().then((values)=>{  // 如果全部欄位通過校驗,會走then方法,裡面可以打印出表單所有欄位(一個object) console.log('成功') console.log(values) }).catch((errInfo)=>{  // 如果有欄位沒聽過校驗,會走catch,裡面可以列印所有校驗失敗的資訊 console.log('失敗')
    console.log(errInfo) }) } render(){ const layout
= { labelCol: { span: 8 }, wrapperCol: { span: 16 }, } return ( <div> <h3>表單校驗-demo</h3> <div> <Form ref={this.formRef} {...layout} // onFinish={this.onFinish} style={{width: '600px',margin:'0 auto'}} > <Row gutter={24}> <Col span={24} key="select1"> <Form.Item label="下拉框1" name="select1" rules={[{ required: true, message: '請輸入使用者名稱!' }, ]} > <Select mode="multiple" showSearch placeholder="下拉框1" // onChange={this.handleChangeSchool} style={{ width: '100%' }} > <Option key='1' value='11'>aa</Option> <Option key='2' value='22'>bb</Option> <Option key='3' value='33'>cc</Option> </Select> </Form.Item> </Col> <Col span={24} key="text1"> <Form.Item label="密碼" name="text1" rules={[ {required: true, message: '請輸入密碼!' }, {min: 6, message: '密碼至少6位!' }, {max: 10,message: '密碼最長10位!'}, ]} > <Input placeholder="text1" /> </Form.Item> </Col> <Col span={24} key="text2"> <Form.Item label="確認密碼" name="text2" rules={[ {required: true, message: '請輸入text1!' }, // {min: 6, message: '確認密碼至少6位!' }, // {max: 10,message: '確認密碼最長10位!'}, { validator: (_, value) =>{ const form = this.formRef.current let text1 = form.getFieldValue('text1') if(value && (value.length < 6 || value.length > 10)) { return Promise.reject('text1必須是6~10位') }else if(text1 != value){ return Promise.reject('兩次密碼不一致') }else { return Promise.resolve() } } } ]} > <Input placeholder="text2" /> </Form.Item> </Col> <Col span={24} key="text3"> <Form.Item label="文字框3" name="text3"> <Input type="number" placeholder="text3" /> </Form.Item> </Col> </Row> <Row> <Col span={24} style={{ textAlign: 'right' }}> <Button type="primary" onClick={this.submit} style={{ marginRight: '8px' }}>提交</Button> </Col> </Row> </Form> </div> </div> ) } } export default FormDemo

2、校驗效果