问题
Below validation method will check for duplicate values in all textBoxes having class name checkForDuplicate
$.validator.addMethod("checkForDuplicate", function(value, element) {
var textValues = [];
$("input.validateLocation").each(function() {
if($(this).val() !== ""){
var doesExisit = ($.inArray($(this).val(), textValues) === -1) ? false : true;
if (doesExisit === false) {
console.log("adding the values to array");
textValues.push($(this).val());
console.log(textValues);
} else {
console.log(textValues);
return false;
}
}
});
return true;
});
but it is not working as intended, It is failing at first textBox only. help me to resolve this.
回答1:
The problem seems to be that you are always returning true from your validate method, so try
$.validator.addMethod("checkForDuplicate", function (value, element) {
var textValues = [],
//initially mark as valid state
valid = true;
$("input.validateLocation").each(function () {
if ($(this).val() !== "") {
var doesExisit = ($.inArray($(this).val(), textValues) === -1) ? false : true;
if (doesExisit === false) {
console.log("adding the values to array");
textValues.push($(this).val());
console.log(textValues);
} else {
console.log(textValues);
//update the state as invalid
valid = false;
return false;
}
}
});
//return the valid state
return valid;
});
Demo: Fiddle
回答2:
try this:
$.validator.addMethod("checkForDuplicate", function(value, element) {
var textValues = [];
$("input.validateLocation").each(function() {
if($(this).val() !== ""){
var doesExisit = ($.inArray($(this).val(), textValues) === -1) ? false : true;
if (doesExisit === false) {
console.log("adding the values to array");
textValues.push($(this).val());
console.log(textValues);
} else {
console.log(textValues);
return false;
}
}
});
});
回答3:
Bit late but try this one, this should solve your problem without adding an array.
$.validator.addMethod("checkForDuplicate", function (value, element) {
//initially mark as valid state
valid = true;
$("input.validateLocation").each(function () {
value1 = $(this).val();
if ($(this).val() !== "") {
$('input.validateLocation').not(this).each(function(){
if($(this).val()==value1){
valid=false;
return false;
}
});
});
//return the valid state
return valid;
};
来源:https://stackoverflow.com/questions/24801985/jquery-validation-add-method-for-checking-duplicate-values-in-a-text-box