victorjonsson / jQuery-Form-Validator

[DISCONTINUED] jQuery plugin that makes it easy to validate user input while keeping your HTML markup clean from javascript code.
971 stars 474 forks source link

Dynamic errorMessage for addValidator #505

Open bewards opened 8 years ago

bewards commented 8 years ago

Added a small custom validator, called different_input_value, to compare the current inputs value against an input in the same form (could extend this to multiple inputs that just have the data attribute without an attr value) to make sure they are not the same. I didn't see an existing validator for this. I would like to change the errorMessage to dynamically display the two inputs placeholder values like so:

"[Secondary Email] must have a different value from [Primary Email]"

Given the following inputs:

<input type="text" name="ma_primary-email" id="ma_primary-email" placeholder="Primary Email" data-validation="email different_input_value" data-validation-different-input="ma_secondary-email" />
<input type="text" name="ma_secondary-email" id="ma_secondary-email" placeholder="Secondary Email" data-validation="email" />

js validator

$.formUtils.addValidator({
    name: 'different_input_value',
    validatorFunction: function (value, $el, config, language, $form) {

        var diffInputId = $el.attr('data-validation-different-input');
        if (helper.exists(diffInputId)) {
            var $diffInput = $form.find('#' + diffInputId);
            if (helper.exists($diffInput)) {
                return $.trim($el.val()) !== $.trim($diffInput.val());
            }
            return false;
        }
        return false;
    },
    errorMessage: 'Recaptcha required',
    errorMessageKey: 'differentInputValueRequired'
});

There may currently be a way to add logic for this in an error callback event, but what if the errorMessage property supported a callback that passed in the $el and the effected input? If there's something already available that I can do, we can just scratch this idea :wink:

victorjonsson commented 8 years ago

The object sent to addValidator is sent by reference and as a consequence, you can change the value of errorMessage in runtime.

$.formUtils.addValidator({
   ...
   validatorFunction: function() {
      if (likeThis()) {
          this.errorMessage = "It's like this...";
          return false;  
      } else if (likeThat()) {
         this.errorMessage = "It's like that...";
         return false;
      } else {
         return true;
      }
   },
   errorMessage: '' // will change in runtime...
})
bewards commented 8 years ago

Good to know! This can be closed. I'll reply if anything goes wrong.