我想验证我的表单,以使我无法在输入框中键入以下代码(如果该代码已存在于列表中)。
<input id="form:inptCode" type="text" name="form:inptCode" class="number">
波纹管是primefaces订单清单元素的html。
<select id="form:choices_values" name="form:choices_values" multiple="true" class="ui-helper-hidden">
<option value="1" selected="selected">1</option>
</select>
因此,列表包含值1。如果我在inputText中键入数字1,则将出现错误消息。
为了实现此目的,我添加了一个方法,当此方法返回false时,我尝试验证表单。我没有使用jQuery验证的丰富经验,实际上我只写了几种方法。
$.validator.addMethod('codExistss', function (value, element) {
var lstChoices = document.getElementById('form:choices_values');
for (i = 0; i < lstChoices.options.length; i++) {
return value === lstChoices.option[i].value;
}
}, "The code already exists.");
$(document).ready(function () {
$('#form').validate({
rules: {
'form:inptCode': {
codExistss: false
}
}
});
});
看来我的代码行不通。那么,您能帮我理解为什么吗?
您遍历所有列表选项:
for (i = 0; i < lstChoices.options.length; i++) {
return value === lstChoices.option[i].value;
}
假设您将有1个以上的选项,那么仅1次条件返回true并破坏您的验证就足够了。
第二件事是您没有为自定义函数打开规则标志:您的codExistss: false
意思是“不要通过此规则验证输入”,将其更改为true。
试试这个:
$.validator.addMethod('codExistss', function (value, element) {
var lstChoices = document.getElementById('form:choices_values');
if(lstChoices.options[lstChoices.selectedIndex].value===value) {return false;}
return true;
},"The code already exists.");
$(document).ready(function () {
$('#form').validate({
rules: {
'form:inptCode': {
// Specify that form:inptCodeshould be validated
// by codExistss rule
codExistss: true
}
}
});
});
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句