kazupon / vue-validator

:white_check_mark: Validator component for Vue.js
MIT License
2.19k stars 431 forks source link

Dynamic error messages for custom validations (Feature) #266

Open ajarti opened 8 years ago

ajarti commented 8 years ago

Hi guys,

I have read the forum and asked on Gitter, but I can not see how to dynamically change a custom validation's error message.

For UX reasons I want to have a text field that allows the user to just add a 'compound' date in the format MMM YYYY and I want to validate this. I want to validate the length of the month and year, make sure the month exists, that the year is within 60 years of now etc etc and would like to not have to make multiple repetitive validations with small changes. Sample code below(excuse simplicity):

Vue.validator('mmmyyyy', {
        message : 'Format should be MMM YYYY e.g. Feb 2006',
        check   : function(val)
        {
            if ( !val ) return false;
            var parts = val.replace(/\s\s+/g, ' ').trim().split(' ');

            // Only 2 parts
            if ( parts.length != 2 ) {
                 this.message = '2 parts are required MMM & YYYY';
                 return false;
            }
            var month = parts[0];
            var year  = parts[1];

            // MMM
            if ( month.length != 3 ) {
                this.message = 'Month should be short e.g. Feb not February';
                return false;
            }

           Etc ... (excluded for brevity)
        }

    });

I tried to convert the message property into a function, but was still unable to set the message. I think this may be a useful feature for more complex validations.

i hope I didn;t miss and example somewhere.

Thanks in advance for your time.

kazupon commented 8 years ago

Thank you for your feed backing!! In v3, I'll try to consider your feedback. 😉

I think that the above complex custom validation code can avoid the splited custom validations. the below code:

The below example code:

<input type="text" v-validate:field1="{
  required: true,
  custom1: { rule: ... },
  custom2: { rule: ... },
  ...
}">
new Vue({
  validators: {
    custom1: {
      message: 'validation error1',
      check: function (val) {
        // something simple validation 
      }
    },
    custom2: {
      message: 'validation error2',
      check: function (val) {
        // something simple validation 
      }
    },
    ...
  }
})
ajarti commented 8 years ago

@kazupon Many thanks for the feedback, and that is just what I have done :)

Thanks for a fantastic tool .. excellent work!