react+antd系列之Form表單(2):格式限制驗證
阿新 • • 發佈:2018-11-21
格式限制
antd中表單的功能很多,下面就為大家整理了一下antd中常用的幾種表單輸入格式驗證:
1. 輸入框不能為空限制,如下:
{getFieldDecorator('name', {
rules: [{
required: true,
message: '名稱不能為空',
}],
})(
<Input placeholder="請輸入名稱" />
)}
2. 輸入框字元限制,如下:
字元長度範圍限制:
{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="請輸入暱稱" />
)}
3. 自定義校驗
{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(); }
validator屬性自定義效驗,必須返回一個callback
4.whitespace空格報錯
{getFieldDecorator('hobody', {
rules: [{
whitespace: true,
message: '不能輸入空格',
} ],
})(
<Input placeholder="請輸入暱稱" />
)}
若輸入只有一個空格,則會報錯
5.pattern正則驗證
{getFieldDecorator('qbc', { rules: [{ message:'只能輸入數字', pattern: /^[0-9]+$/ } ], })( <Input placeholder="請輸入ABC" /> )}
如果輸入的不是數字,則提示錯誤
完整程式碼地址:
https://gitee.com/hope93/antd-form2