【发布时间】:2019-07-31 00:14:57
【问题描述】:
我写了一个这样的自定义验证器:
created () {
this.$validator.extend('validateCert', {
getMessage: (field) => {
return field + ' is not a valid certificate';
},
validate: (value) => {
return value.startsWith('-----BEGIN CERTIFICATE-----') && value.endsWith('-----END CERTIFICATE-----');
}
});
}
我已将它附加到模态框内的文本区域:
<div class="pb-3 mr-4">
<b-form-textarea
type="text"
v-validate="'required|validateCert'"
data-vv-validate-on="change"
v-model.trim="signedCerts[index]"
data-vv-scope="uploadCert"
:name="'certificate_' + index"
:class="[{'is-invalid': errors.has('certificate_' + index)}]"
rows="15"/>
<fr-validation-error :validatorErrors="errors" :fieldName="'certificate_' + index"></fr-validation-error>
</div>
然后 - 在按钮上单击我执行以下操作:
uploadCerts (event) {
let idmInstance = this.getRequestService(),
body = {
fromCSR: true,
certs: _.each(this.signedCerts, (cert) => {
JSON.stringify(cert);
})
};
this.$validator.validateAll('uploadCert').then((valid) => {
// Prevent modal from closing
event.preventDefault();
if (valid) { // some more logic
如果我检查计算的错误对象,我会看到我的验证失败:
{
"items": [
{
"id": "19",
"field": "certificate_0",
"msg": "certificate_0 is not a valid certificate",
"rule": "validateCert",
"scope": "uploadCert",
"regenerate": {
"_custom": {
"type": "function",
"display": "<span>ƒ</span> regenerate()"
}
}
}
]
}
并且“有效”的值(真或假)在任何时候都是准确的。我只是没有看到我的错误类被触发。
【问题讨论】:
-
你在哪里定义
errors?是reactive?是在您的data部分中定义的吗?你怎么变异它?如果您使用索引运算符[],您的逻辑将不会被调用。如果是这种情况,您将需要使用Vue.set。 -
errors由 veeValidate 提供。 -
我一眼看不出你的代码有什么不好的地方。我总是在使用
errors之前检查它是否存在,以避免组件仍在加载时出现异常,例如,在您的情况下:[{'is-invalid': errors && errors.has('certificate_' + index)}]。但我认为这与您的问题无关。
标签: javascript validation vue.js vee-validate