antd 表单的两种校验方式
1.声明式表单验证:
| 12345678910111213141516171819202122 | ``<Form.Item`` ``name=``"username"`` ``rules={[`` ``{`` ``required: ``true``,`` ``message: ``'Please input your Username!'``,`` ``},`` ``{`` ``max: 20,`` ``message: ``'最长20位!'``,`` ``},`` ``{`` ``min: 5,`` ``message: ``'至少5位!!'``,`` ``}, {`` ``pattern: /^[A-Za-z\d_]+$/,`` ``message: ``'自能包含字母数字下划线字符!'``,`` ``},`` ``]}`` ``>`` ``<Input prefix={<UserOutlined className=``"site-form-item-icon" />} placeholder=``"Username" />`` ``</Form.Item> |
|---|
2. validator自定义式验证:
| 1234567891011121314151617181920 | ``<Form.Item`` ``name=``"password"`` ``rules={[`` ``{`` ``validator: (_, value) =>{`` ``if``(value.length >= 6 && value.length<=10) {`` ``return Promise.resolve()`` ``}``else``{`` ``return Promise.reject(``'密码长度必须是6~10位'``)`` ``}`` ``}`` ``}`` ``]}`` ``>`` ``<Input`` ``prefix={<LockOutlined className=``"site-form-item-icon" />}`` ``type=``"password"`` ``placeholder=``"Password"`` ``/>`` ``</Form.Item> |
|---|
antd-design-vue form表单验证,禁止输入中文,只数字,等验证要怎么写呀~~
因为是在表单里写的,所以有点迷,不知道要怎么写..
请大神给个思路~~~
<a-form-item v-bind="formStyle" label="别名(英文)">
<a-input
placeholder="请输入别名"
v-decorator="['menuPath', { rules: [ { required: true, message: '请输入别名' }, { validator: (rule, value, cb) => this.changeKey(rule, value, cb) } ] }]"
/>
</a-form-item>
把采纳给了楼下
我现在的解决办法如下: 感觉这样更方便点儿
<a-form-item v-bind="formStyle" label="别名(英文)">
<a-input
placeholder="请输入别名"
maxlength="50"
minlength="3"
v-decorator="['menuPath', { rules: [
{ required: true, message: '请输入别名' }
],
getValueFromEvent: (event) => {
return event.target.value.replace(/[\u4E00-\u9FA5]/g,'')
}
}]"
/>
</a-form-item>
相关代码
// 只列举一个表单项,其他的规则都是必填。
<a-form :form="form" @submit="handleSubmit" layout="vertical">
<a-form-item
label="标题"
:labelCol="formItemLayout.labelCol"
:wrapperCol="formItemLayout.wrapperCol">
<a-input
v-decorator="[
'title',
{initialValue: formData.title, rules: [{ required: true, message: '请输入标题' }]}
]"
placeholder="标题" />
</a-form-item>
</a-form>
// 提交
async handleSubmit (e) {
event.preventDefault()
this.form.validateFields((err, values) => {
if (!err) {
Object.assign(this.formData, values)
Object.assign(this.formData, { updatedAt: Date.now() })
console.log('提交信息成功', this.formData)
}
})
if (this.formData.id) {
const res = await updateBanner(this.formData)
console.log('编辑', res)
} else {
const res = await createBanner(this.formData)
console.log('新增', res)
}
},
以下是一段手机号的的自定义校验,在提交表单的时候form.validateFields总是出现错误,方法无法向下执行Vue+Antd表单校验form.validateFields执行错误的解决方法
在自定义校验里面每一个判断都要调用callback(),要保证方法最后执行到的永远都是callback()
//自定义校验(检查手机号是否输入正确)
checkPhone(rule, value, callback) {
if (value != null && value != "") {
var reg = /^1[3456789]\d{9}$/;
if (!reg.test(value)) callback(new Error("手机号格式不正确"));
//调用callback
else callback();
} else {
callback();
}
}