因此,我的电子邮件/用户表单元素上的异步验证程序存在问题。每次输入字母时,都会检查是否有效。如果电子邮件是30chars,则超过30个电话!任何人都知道最好的方式来消除一个笨拙的自定义验证器吗?当我尝试使用防抖功能时,由于期望得到响应,因此我从vuelidate那里收到了各种错误。
<div class="form-group">
<label for="emailAddress">Email address</label>
<input type="email" class="form-control col-md-6 col-sm-12" v-bind:class="{ 'is-invalid': $v.user.email.$error }" id="emailAddress" v-model.trim="$v.user.email.$model" @change="delayTouch($v.user.email)" aria-describedby="emailHelp" placeholder="email@example.com">
<small v-if="!$v.user.email.$error" id="emailHelp" class="form-text text-muted">We'll never share your email with anyone.</small>
<div class="error invalid-feedback" v-if="!$v.user.email.required">Email address is required.</div>
<div class="error invalid-feedback" v-if="!$v.user.email.email">This is not a valid email address.</div>
<div class="error invalid-feedback" v-if="!$v.user.email.uniqueEmail">This email already has an account.</div>
</div>
<script>
import { required, sameAs, minLength, maxLength, email } from 'vuelidate/lib/validators'
import webapi from '../services/WebApiService'
import api from '../services/ApiService'
const touchMap = new WeakMap();
const uniqueEmail = async (value) => {
console.log(value);
if (value === '') return true;
return await api.get('/user/checkEmail/'+value)
.then((response) => {
console.log(response.data);
if (response.data.success !== undefined) {
console.log("Email already has an account");
return false;
}
return true;
});
}
export default {
name: "Register",
data() {
return {
errorMsg: '',
showError: false,
user: {
firstName: '',
lastName: '',
email: '',
password: '',
password2: ''
}
}
},
validations: {
user: {
firstName: {
required,
maxLength: maxLength(64)
},
lastName: {
required,
maxLength: maxLength(64)
},
email: {
required,
email,
uniqueEmail //Custom async validator
},
password: {
required,
minLength: minLength(6)
},
password2: {
sameAsPassword: sameAs('password')
}
}
},
methods: {
onSubmit(user) {
console.log(user);
/*deleted*/
},
delayTouch($v) {
console.log($v);
$v.$reset()
if (touchMap.has($v)) {
clearTimeout(touchMap.get($v))
}
touchMap.set($v, setTimeout($v.$touch, 1250))
}
}
}
</script>
当我尝试用去抖来包装异步函数时,veelidate不喜欢它,因此我将其删除。不确定如何限制自定义“ uniqueEmail”验证器。
答案 0 :(得分:1)
正如“泰迪·马尔科夫”(Teddy Markov)所说,您可以在输入模糊事件中调用$v.yourValidation.$touch()
。我认为这是使用Vuelidate的更有效的方法。
<input type="email" class="form-control col-md-6 col-sm-12"
:class="{ 'is-invalid': !$v.user.email.$anyError }"
id="emailAddress" v-model.trim="$v.user.email.$model"
@change="delayTouch($v.user.email)"
@blur="$v.user.email.$touch()"
aria-describedby="emailHelp"
placeholder="email@example.com"
>
答案 1 :(得分:0)
我发现最好的方法是与正则表达式结合使用以发送电子邮件 如果正则表达式测试通过,则继续检查是否唯一-否则完全跳过检查。