victorjonsson / jQuery-Form-Validator

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

Call validator function #421

Open Billy- opened 8 years ago

Billy- commented 8 years ago

Is it possible to call a validator function without doing any of the other Jazz (i.e altering the dom etc.)

For context, I want to create a custom validator which combines two other validators. Imagine I want a field that will accept an email or a phone number (let's just use the number validator for this example), I would like to be able to do something like:

validatorFunction : function(val){
  return $.formUtils.validateValue(val, 'email') || $.formUtils.validateValue(val, 'number');
}

Is this possible currently?

victorjonsson commented 8 years ago

All validators are attached to $.formUtils.validators. So you could do something like this:

validatorFunction: function(value, $el, config, language, $form) {
   return $.formUtils.validators.validate_email.validatorFunction(value, $el, config, language, $form) || $.formUtils.validators.validate_number.validatorFunction(value, $el, config, language, $form);
}

This would'nt be advised though. It will not necessarily be supported by upcoming versions of the plugin. I'm thinking that this could be part of the new module named logic. Having an attribute like data-validation-statement="validator || validator" we could add support for && as well.

<input type="text" data-validation="statement" data-validation-statement="email || number" />
Billy- commented 8 years ago

I think it would be more useful to give access to calling the validator functions by passing a value, then you could implement more complex validators as well as logic, perhaps you want to parse or modify the value in some way and then run it through another validator.

Allowing the plugin to be used this way means you would also be able to use it to validate input from other sources as well, unrelated to the form :)

victorjonsson commented 8 years ago

Sounds like good ideas but the design of this system has emerged over time and this use case has never come up. Many of the validators requires access to the DOM and that's the reason why the interface looks like it does.