Ant UI 的表单校验

    技术2023-08-09  80

    ```React import React from "react"; import { Card, Form, Input, Button, message, Icon, Checkbox } from "antd"; const FormItem = Form.Item; // 表单的单行 class FormLogin extends React.Component{ handleSubmit = ()=>{ let userInfo = this.props.form.getFieldsValue(); // 获取表单的所有属性 this.props.form.validateFields((err,values)=>{ if(!err){ message.success(`${userInfo.userName}欢迎您 ,当前密码为:${userInfo.userPwd}`) } }) } render(){ const { getFieldDecorator } = this.props.form; return ( <div> <Card title="登录水平表单" style={{marginTop:10}}> <Form style={{width:300}}> <FormItem> { getFieldDecorator('userName',{ initialValue:'', rules:[ { required:true, message:'用户名不能为空' }, { min:5,max:10, message:'长度不在范围内' }, { pattern:new RegExp('^\\w+$','g'), message:'用户名必须为字母或者数字' } ] })( <Input prefix={<Icon type="user"/>} placeholder="请输入用户名" /> ) } </FormItem> <FormItem> { getFieldDecorator('userPwd', { initialValue: '', rules: [] })( <Input prefix={<Icon type="lock" />} type="password" placeholder="请输入密码" /> ) } </FormItem> <FormItem> { getFieldDecorator('remember', { valuePropName:'checked', initialValue: true })( <Checkbox>记住密码</Checkbox> ) } <a href="#" style={{float:'right'}}>忘记密码</a> </FormItem> <FormItem> <Button type="primary" onClick={this.handleSubmit}>登录</Button> </FormItem> </Form> </Card> </div> ); } } // 使用getFieldDecorator ,因为是antd的form的属性,所以需要导出form组件,使用这句话 export default Form.create()(FormLogin); ![login](https://img-blog.csdnimg.cn/20200703152453479.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzM3MjQxOTM0,size_16,color_FFFFFF,t_70)
    Processed: 0.009, SQL: 9