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 475 forks source link

Different messages on multiple validation of a single field #569

Open SvetlinStaev opened 7 years ago

SvetlinStaev commented 7 years ago

I would like to validate a field based on a few criteria and I have created custom validators for each of them.

I load the criteria:

                validate : {
                    'listing[title]' : {
                        'validation': 'caps_abuse, phone_abuse, required',
                        '_data-sanitize': 'trim capitalize',
                        'error-msg': 'The title is required for the form'
                    },

with the following validators:

            $.formUtils.addValidator({
                name : 'caps_abuse',
                validatorFunction : function(value, $el, config, language, $form) {
                    var totalLetters = value.length,
                        split = value.split(''),
                        caps = $.grep(split, function(letter) {
                            return letter.toLowerCase() != letter;
                        }),
                        percent = totalLetters > 0 ? (100 * caps.length) / totalLetters : 0;
                    return percent < 75;
                },
                errorMessage : 'Please do not use extensively caps for the title',
                errorMessageKey: 'caps-abuse-error'
            });

            $.formUtils.addValidator({
                name : 'phone_abuse',
                validatorFunction : function(value, $el, config, language, $form) {
                    var phoneTest = new RegExp(/([0-9][7-9][0-9\(\)\-\s*\.\,]{6,9})/gi);
                    return !phoneTest.test(value);
                },
                errorMessage : 'Phone numbers are not allowed',
                errorMessageKey: 'phone-abuse-error'
            });

This checks if the text is all caps, if it has a phone number in it and the default required validator.

The problem is regardless of the type of the failed validation only the text from the data-validation-error-msg attribute is shown. Is there a way to display the errorMessage from each of the custom validators when the validation fails for that particular validator?

victorjonsson commented 7 years ago

You can declare a message for each validation rule.

<input ..
   data-validation-error-msg-phone_abuse="..." 
   data-validation-error-msg-caps_abuse="...">

http://www.formvalidator.net/#localization_inline


The error messages declared by the validator will be used if you leave out the inline declaration (data-validation-error-msg). If the input has an inline declaration it will be used every time the input gets invalid, instead of the messages coming from the validators.