prevent Duplicate values using Jquery Validation

前端 未结 11 1890
深忆病人
深忆病人 2020-12-04 22:28

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.<

11条回答
  •  庸人自扰
    2020-12-04 23:02

    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.

提交回复
热议问题