react + antd Form表單校驗


  • 非空限制

{getFieldDecorator('name', {
rules: [{
required: true,
message: '名稱不能為空',
}],
})(
<Input placeholder="請輸入名稱" />
)}
  • 字符串限制

  范圍限制:

                  {getFieldDecorator('password', {
                    rules: [{
                      required: true,
                      message: '密碼不能為空',
                    }, {
                      min:4,
                      message: '密碼不能少於4個字符',
                    }, {
                      max:6,
                      message: '密碼不能大於6個字符',
                    }],
                  })(
                    <Input placeholder="請輸入密碼" type="password"/>
                  )}

  長度限制:

                  {getFieldDecorator('nickname', {
                    rules: [{
                      required: true,
                      message: '昵稱不能為空',
                    }, {
                      len: 4,
                      message: '長度需4個字符',
                    }],
                  })(
                    <Input placeholder="請輸入昵稱" />
                  )}
  • 自定義校驗

                  {getFieldDecorator('passwordcomfire', {
                    rules: [{
                      required: true,
                      message: '請再次輸入密碼',
                    }, {
                      validator: passwordValidator
                    }],
                  })(
                    <Input placeholder="請輸入密碼" type="password"/>
                  )}

                  //  密碼驗證
                  const passwordValidator = (rule, value, callback) => {
                    const { getFieldValue } = form;
                    if (value && value !== getFieldValue('password')) {
                    callback('兩次輸入不一致!')
                  }
  
                    // 必須總是返回一個 callback,否則 validateFields 無法響應
                    callback();
                  }
  • 空格校驗

                  {getFieldDecorator('hobody', {
                    rules: [{
                      whitespace: true,
                      message: '不能輸入空格',
                    } ],
                  })(
                    <Input placeholder="請輸入昵稱" />
                  )}
  • 正則校驗

                  {getFieldDecorator('qbc', {
                    rules: [{
                      message:'只能輸入數字',
                      pattern: /^[0-9]+$/
                    } ],
                  })(
                    <Input placeholder="請輸入ABC" />
                  )}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM