Form form of react+antd series: format restriction validation

Posted by mikefrederick on Wed, 04 Dec 2019 06:58:09 +0100

Format restriction

There are many functions of forms in antd. Here are some common forms input format validation in antd:

1. The input box cannot be empty, as follows:

  {getFieldDecorator('name', {
            rules: [{
            required: true,
            message: 'Name cannot be empty',
          }],
         })(
      <Input placeholder="Please enter a name" />
  )}

2. The character limit of the input box is as follows:

Character length range limit:

   {getFieldDecorator('password', {
            rules: [{
              required: true,
              message: 'Password cannot be empty',
            }, {
            min:4,
            message: 'Password cannot be less than 4 characters',
          }, {
            max:6,
            message: 'Password cannot be greater than 6 characters',
          }],
         })(
        <Input placeholder="Please input a password" type="password"/>
   )}

Character length limit:

  {getFieldDecorator('nickname', {
            rules: [{
            required: true,
            message: 'Nickname cannot be empty',
          }, {
            len: 4,
            message: '4 characters long',
          }],
         })(
       <Input placeholder="Please enter a nickname" />
  )}

3. User defined verification

   {getFieldDecorator('passwordcomfire', {
            rules: [{
              required: true,
              message: 'Please enter the password again',
            }, {
              validator: passwordValidator
          }],
         })(
            <Input placeholder="Please input a password" type="password"/>
   )}
   
     //  Password verification
  const passwordValidator = (rule, value, callback) => {
    const { getFieldValue } = form;
    if (value && value !== getFieldValue('password')) {
        callback('The two inputs are inconsistent!')
    }

    // A callback must always be returned, otherwise validateFields cannot respond
    callback();
  }

validator attribute custom validation, a callback must be returned

4.whitespace error

  {getFieldDecorator('hobody', {
            rules: [{
              whitespace: true,
              message: 'Space cannot be entered',
          } ],
         })(
            <Input placeholder="Please enter a nickname" />
  )}

If there is only one space, an error will be reported

5.pattern regular verification

 {getFieldDecorator('qbc', {
            rules: [{
              message:'Only numbers can be entered',
              pattern: /^[0-9]+$/
          } ],
         })(
            <Input placeholder="Please input ABC" />
)}

If you do not enter a number, you will be prompted with an error

Full code address:
https://gitee.com/hope93/antd...

Topics: Javascript less Attribute