之前很少用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={{ '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={{ '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、校验效果