I'm using jQuery Form validator, I created a custom validator to check if the input value already exists, but It's not working.
var seen = {};
$.formUtils.addValidator({
name: 'value_exists',
validatorFunction: function(value, $el, config, language, $form) {
if (seen[value]) {
return false;
} else {
seen[value] = true;
return true;
}
},
errorMessage: 'This value exits already',
errorMessageKey: ''
});
Edit : For example I type in the first input the value TEST, and then in the second I type TEST again, whice normally shows the error. when I try to replace that value with another one (MASTER in this example) the error does not go away.
Here is what console.log(seen)
shows :
Object {TEST: true, M: true, MAS: true, MAST: true, MASTER: true}
Solved the problem with a better algorithm :
$.formUtils.addValidator({
name: 'duplicated',
validatorFunction : function (value,$el,config,language,$form){
var ret = true;
$form.find('[name="' + $el.attr('name') + '"]').each(function(index, elm) {
if($el[0].id !== elm.id && elm.value === value) ret = false;
});
return ret;
},
errorMessage : 'The value exists already.',
errorMessageKey : ''
});
What I do here is : for all inputs with X name, for each input, if the id's are different(to prevent the element to compare itself), and the value is the same, throw an error (duplicate).