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" /> )}
让每一天过的有意义!