I have form and form text field which generates dynamically using JSP. And I\'m using Jquery validation but want to add functionlaty to prevent duplicate entry in the form.<
Here is another slightly modified answer from the previous answers.
This one checks duplicate values against form elements with the same name (which is perfectly valid from an HTML standpoint).
For example:
Note: You don't even need the ID, it's just shown for completeness.
The following custom validator will validate these inputs as having unique values:
$.validator.addMethod('unique', (value, element) => {
var timeRepeated = 0;
if (value && value.length)
{
$(`input[name=${(element as HTMLFormElement).name}]`).each(function ()
{
if ($(this).val() === value)
{
timeRepeated++;
}
});
}
return timeRepeated === 1 || timeRepeated === 0;
});
Note: This is TypeScript, but easily convertible back to pure JS.
Be sure to enable the rule elsewhere, e.g.:
var myValidationRules = {
emailField: {
unique: true
}
}
And put a validation message on the validator definition above, or use the validator.settings.messages property.