Search code examples
javascriptjquery-form-validator

validate.js different functions on invalid


I'm using validation.js plugin and in the case I want it I was trying to make some changes to it but after a lot of thinking and testing and searching I got nothing , at least nothing I wanted... I have this code:

$("#form").validate({
    rules: 
    {
        phone: 
        {
            required: true,
            number: true,
            minlength: 6
        }
    },
    messages:
    {
        phone: 
        {
            required: 'This field is required',
            number: 'Invalid phone number',
            minlength: 'Minimum length: 6'
        }
    }
});

every thing is okay but I want it to run some different functions in addition to showing massages , for example when the user type sth less than 6 char , show massage AND RUN Function ONE , if the user type sth except nums it shows massage and also RUN Function TWO

sth like this:

    $("#form").validate({
        rules: 
        {
            phone: 
            {
                required: true,
                number: true,
                minlength: 6
            }
        },
        messages:
        {
            phone: 
            {
                required: 'This field is required',
                number: 'Invalid phone number' + function TWO,
                minlength: 'Minimum length: 6' + function ONE
            }
        }
    });

can anyone help me please?


Solution

  • You can use a callback function instead of a string as the value for a custom message. Just make sure to return the message from that function. That way you can do any operation before outputting the message. The callback function takes two arguments, first is the value being passed to the rule, and second is the element.

    messages

    ...Each message can be a String or a Callback. The callback is called in the scope of the validator, with the rule's parameters as the first argument and the element as the second, and must return a String to display as the message.

    messages:
    {
      phone: 
      {
        required: 'This field is required',
        number: function(rule, elem) {
          doSomeStuff('run before number message');
          return 'Invalid phone number';
        },
        minlength: function(rule, elem) {
          doSomeStuff('run before minlength message');
          return 'Minimum length: 6';
        }
      }
    }
    

    Check the -- JSFiddle Example -- here.