我遇到了以下问题。这是我要验证的输入
<input type="text" name="vatid" data-parsley-remote data-parsley-remote-validator='vatid'/>
这是 asyncValidator
$('[name="vatid"]').parsley()
.addAsyncValidator('vatid', function (xhr) {
return 404 === xhr.status;
}, confighandler.getConfig().apiUrl + '/checkvatids');
我的问题是,如果用户没有输入值,欧芹也会向 api 发送请求(在表单提交时),然后触发错误消息。如何避免这种情况并仅验证用户是否输入了某些内容?
更新
非常感谢 milz,我得到了以下解决方案,它的效果非常好:)
define([
'jquery',
'confighandler',
'requirejs-i18n!nls/labels',
'parsleyjs'
], function($, confighandler, Labels) {
'use strict';
return {
initialize: function() {
// add custom validators
window.ParsleyValidator
.addValidator('vatid', function(val) {
var isvalid;
$.ajax({
url: confighandler.getConfig().apiUrl + '/checkvatids/' + val,
dataType: 'json',
type: 'get',
async: false,
success: function(response) {
isvalid = (response.result.data.isvalid === 'true') ? true : false;
},
error: function() {
isvalid = false;
}
});
return isvalid;
}, 32).addMessage('de', 'vatid', Labels.validation.vatid);
}
};
});
最佳答案
您可以实现这一点,但不能使用 ParsleyRemote。远程验证器的问题是,在进行远程 ajax 调用之前,您无法验证该值是否为空。
此问题的可能解决方案是添加自定义验证器 .addValidator
然后发出 ajax 调用。
在这种情况下,您甚至不需要检查输入是否有任何内容,因为验证器仅在输入不为空时执行。
<input type="text" name="vatid" data-parsley-vatid />
<script>
$(document).ready(function() {
window.ParsleyValidator
.addValidator('vatid', function (value, requirement) {
var response = false;
$.ajax({
url: confighandler.getConfig().apiUrl + '/checkvatids',
data: {vatid: value},
dataType: 'json',
type: 'get',
async: false,
success: function(data) {
response = true;
},
error: function() {
response = false;
}
});
return response;
}, 32)
.addMessage('en', 'vatid', 'Vatid is invalid.');
});
</script>
您还可以查看以下可以提供附加信息的问题:Parsley.js Trigger Error on AJAX
关于javascript - Parsley.js 如果值为空,请勿使用远程验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25989490/