我有一个电子邮件字段
<template>
<v-form v-model="valid">
<v-text-field
label="Name"
v-model="name"
:rules="nameRules"
:counter="10"
required
></v-text-field>
<v-text-field
label="E-mail"
v-model="email"
:rules="emailRules"
></v-text-field>
</v-form>
</template>和验证规则,比如,
<script>
export default {
data: () => ({
valid: false,
name: '',
nameRules: [
v => !!v || 'Name is required',
v => v.length <= 10 || 'Name must be less than 10 characters'
],
email: '',
emailRules: [
v => /^\w+([.-]?\w+)*@\w+([.-]?\w+)*(\.\w{2,3})+$/.test(v) || 'E-mail must be valid'
]
})
}
</script>但是当我提交表单时它会验证表单,只有当email.length>0时我才需要验证电子邮件。ie电子邮件不是必填字段,但如果键入电子邮件,则必须进行验证。
我也尝试过,当我像这样在脚本中更改:rules="[emailRules.em]"时
emailRules: {
em:v => {
if(v.length > 0 && /^\w+([.-]?\w+)*@\w+([.-]?\w+)*(\.\w{2,3})+$/.test(v) )
return ''E-mail must be valid';
return true;
}
}它总是返回true
发布于 2020-01-05 17:16:59
只需在规则的开头添加条件!v:
emailRules: [
v => !v || /^\w+([.-]?\w+)*@\w+([.-]?\w+)*(\.\w{2,3})+$/.test(v) || 'E-mail must be valid'
]发布于 2018-09-22 00:38:55
这对我很有效。
email: value => {
if(value.length > 0) {
const pattern = /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return pattern.test(value) || 'Invalid e-mail.';
}
}发布于 2019-04-16 14:03:45
看看这个..
emailRules: [ v => /.+@.+/.test(v) || 'Invalid Email address' ]https://stackoverflow.com/questions/50039793
复制相似问题