jQuery-Form-Validator icon indicating copy to clipboard operation
jQuery-Form-Validator copied to clipboard

Different error message on different logic in custom validation

Open naqib83 opened this issue 9 years ago • 7 comments
trafficstars

Hi, I am trying to implement a custom validation which will contain different check. Depending on different checks the function will show different error message. Is it possible? if Yes, can give me an example?

What I am trying to do:

$.formUtils.addValidator({
  name : 'even_number',
  validatorFunction : function(value, $el, config, language, $form) {
    if(value=='white'){
        return true;
    } else if(value=='green') {
        return false
    } else {
        if (value=='red'){
            return false
        }
    }
  },
  //for green
  errorMessage : 'green error message',
  errorMessageKey: 'badEvenNumberGreen'

  //for red
  errorMessage : 'red error message',
  errorMessageKey: 'badEvenNumberRed'
});

naqib83 avatar Aug 09 '16 18:08 naqib83

The error message that will be displayed, when an input is invalid, gets resolved in the following steps:

1) Validator specific error message declared by invalid input Looking if it exists an attribute for the specific validator that failed. data-validation-error-msg-[VALIDATOR]

<input name="user"
  data-validation="required alphanumeric"
  data-validation-error-msg-required="You must enter a user name"
  data-validation-error-msg-alphanumeric="User name may only contain alphanumeric characters"/>

2) Generic error message declared by invalid input Looking at the attribute data-validation-error-msg

<input name="user"
  data-validation="required alphanumeric"
  data-validation-error-msg="You must enter a user name, containing only alphanumeric characters" />

3) Validator object property Use the property errorMessage declared on the validator object, as long it doesn't have a falsy value.

4) Use a predefined error dialog Use the property errorMessageKey declared on the validator object, referring to any of the predefined error messages.


This means that you can change the value of errorMessage in "runtime".


var MyCustomValidator = {
  name : 'custom_validation',
  validatorFunction : function(value, $el, config, language, $form) {
    this.errorMessage = 'Default error message...';
    if(value=='white'){
        return true;
    } else if(value=='green') {
        this.errorMessage = 'Green error message';
        return false
    } else {
        if (value=='red'){
            this.errorMessage = 'Red error message';
            return false
        }
    }
  },
  errorMessage : '',
  errorMessageKey: false
};

$.formUtils.addValidator(MyCustomValidator);

victorjonsson avatar Aug 10 '16 06:08 victorjonsson

Hi, I have tried to implement validation like you showed. But it does not work. Here is my code and this is what I am trying to implement. var MyCustomValidator = { name : 'wean_calf_id', validatorFunction : function(value, $el, config, language, $form) { $.get("jsp/Select_All_Calf_Info.jsp", function(data){ //console.log(data); var birthStageCalfIDs = []; _.map(data.birth_stage, function(ele, idx, list) { birthStageCalfIDs.push(ele.animal_id); }); var response = _.contains(birthStageCalfIDs, value); //console.log(response); this.errorMessage = 'Input valid calf ID'; if(response == false){ this.errorMessage = 'Does not exist in birth'; return false } else { var response = _.contains(weaningStageCalfIDs, value); if(response == true){ this.errorMessage = 'Already exist in weaning'; return false } else { return true; } }

        });
  },
  errorMessage : 'show',
  errorMessageKey: false
};

$.formUtils.addValidator(MyCustomValidator);

And can I show success message as well?

naqib83 avatar Aug 11 '16 21:08 naqib83

Your validator function does not return anything. In this case the suggestion would be to do the entire validation on server side and use the server validation instead.

victorjonsson avatar Aug 11 '16 23:08 victorjonsson

You can user $.ajax and send sync ajax request.

for example

$.formUtils.addValidator({
        name: 'check_username',
        validatorFunction: function (value, $el, config, language, $form) {
            var url = ""; //url for your ajax request
            var ret = false;
            that = this;
            $.ajax({
                type: 'POST',
                url: url,
                data: {}, // data to send for ajax request
                success: function (res) {
                    if (res.status) {
                        ret = true; // if data is valid return true
                    } else {
                        that.errorMessage = "dynamic error"; //error message you want to set
                        ret = false;
                    }
                },
                async: false
            });
            return ret;
        },
        errorMessage: '',
        errorMessageKey: false
    });

deveshgoyal avatar Jun 28 '17 13:06 deveshgoyal

I would advise against using synchronous ajax requests since it's hard to foresee the possible side effects.

Support for async validators is available since release #497 (not yet published on formvalidator.net)

$.formUtils.addValidator({
  name: 'check_username',
  validatorFunction: function (value, $el, config, language, $form, eventContext) {
    var url = ""; //url for your ajax request
    var that = this;
    var asyncValidation = $.formUtils.asyncValidation(this.name, $input, $form);
    return asyncValidation.run(eventContext, function(done) {
      $.ajax({
        type: 'POST',
        url: url,
        data: {}, // data to send for ajax request
        success: function (res) {
          if (res.status) {
            done(true); // if data is valid return true
          } else {
            that.errorMessage = "dynamic error"; //error message you want to set
            done(false);
          }
        }
      });
    });
  },
  errorMessage: '',
  errorMessageKey: false
});

victorjonsson avatar Jun 29 '17 18:06 victorjonsson

$.formUtils.addValidator({
  name : 'even_number',
  validatorFunction : function(value, $el, config, language, $form) {
    if(value=='white'){
        return true;
    } else if(value=='green') {
        this.errorMessage = $($el).data('validation-error-msg-even_number'); //or any custom error msg
        return false
    } else {
        if (value=='red'){
             this.errorMessage = 'Custome error msg'; 
            return false
        }
    }
  },
   // errorMessage : 'green error message', //DELETE errorMessage:  ' ' FROM MAIN BODY OF  $.formUtils.addValidator()
  errorMessageKey: 'badEvenNumberGreen'

ElnazIghani avatar Jul 19 '17 06:07 ElnazIghani

works for me

$.formUtils.addValidator({
  name : 'adultcheck',
  validatorFunction : function(value) {
    var birthDate = new Date(value);
    var difdt = new Date(new Date() - birthDate);
    var age=difdt.toISOString().slice(0, 4) - 1970;
    if (age >= 18) {
        return true;
    }
    else if(age<0){
    	this.errorMessage="Not yet born!";
    	return false;
    }
    else{
    	this.errorMessage="Your age is under 18!";
	    return false;
    }	    
  },
});
$.validate();

rakibdevs avatar Jul 21 '19 04:07 rakibdevs