我試圖執行異步驗證我的Vue.js組件之一,使用vue-validator,跟隨this example。我想檢查用戶提供的電子郵件是否已被使用。自定義異步vue驗證器打破驗證組件
這是驗證器實現我目前正在掙扎:
Vue.validator('emailUnique', {
message: 'this e-mail address has already been taken',
check: function (val) {
return Vue.http({
url: '/validate/email-unique',
method: 'POST',
data: {
email: val
}
}).then(
function (response) { // success
console.log('success');
return Promise.resolve();
},
function (response) { // error
console.log('error');
return Promise.reject();
}
).catch(function(error) {
console.log('catch');
return Promise.reject();
});
}
});
,我在我的組件使用像這樣:
<div>
<validator name="userValidator">
<form novalidate class="form-group" v-on:submit.prevent="submitUser">
<div class="form-group">
<label for="email">E-Mail</label>
<input id="email" name="email" type="email" class="form-control"
placeholder="[email protected]"
v-model="user.email" required v-validate:email="{ required: true, email: true, emailUnique: true }">
<div class="form-validation-error" v-if="$userValidator.email.required && $userValidator.email.touched">
<span>this field is required</span>
</div>
<div class="form-validation-error" v-if="$userValidator.email.email && $userValidator.email.touched">
<span>not a valid e-mail address</span>
</div>
<div class="form-validation-error" v-if="$userValidator.email.emailUnique && $userValidator.email.touched">
<span>this e-mail address has already been taken</span>
</div>
</div>
</form>
</validator>
</div>
不幸的是,這打破了整個驗證對象的電子郵件:
[Vue warn]: Error when evaluating expression "$userValidator.email.required && $userValidator.email.touched".
TypeError: scope.$userValidator.email is undefined
如果我不註冊emailUnique
驗證程序,另外兩個驗證規則正常工作。 此外,請求/validate/email-unique
發佈正確,並收到預期的返回值(只是一個json_encoded響應true/false
),我看到相應的console.log()
輸出('success', 'error', 'catch'
),所以我猜測返回值爲檢查函數isn' t正確並導致vue-validator
失敗。
Vue.http
雖然返回Promise
,所以根據文檔和上面鏈接的示例,應該沒問題。我也試圖從.then()
子句中返回true
或false
,但仍然Vue.http
返回Promise
(這顯然困擾vue-validator
- 也許Promise
對象,我返回的形式vue-validator
預計不會)。
對此有任何提示嗎?
在撰寫本文時,我還在vue 1.0.16(但已經在'vue-validator 2.0.0'上),更新了vue到'vue 1.0.21'解決了這個問題。非常感謝! – falloutghst