5

I am using jquery validation plugin

I added a custom method using addmethod which in turn calls another method to check for valid UK telephone number

here is my code (simplified):

html

<form id="myform">
  <label for="field">Required, telephone: </label>
  <input class="required" id="field" name="field" />
  <br/>
  <input type="submit" value="Submit" />
</form>

jquery

$(document).ready(function(){
    $("#myform").validate({
        rules:{
            field:{
                required:true;
                UKTelNumber:true
            }
        }       
    });
});

jQuery.validator.addMethod("UKTelNumber", function(value,element) {

    if (!checkUKTelephone (value)) {
        alert (telNumberErrors[telNumberErrorNo]);
        return false;
    }
    else {
        return true
    }       
},jQuery.validator.format(telNumberErrors[telNumberErrorNo]));

The function checkUKTelephone sets the value of var telNumberErrorNo according to the type of error. All the error messages are there in an array telNumberErrors.

Now my requirement is that how to show those error messages that is being alerted now.

passing jQuery.validator.format(telNumberErrors[telNumberErrorNo]) as message (third option) of addMethod is not helping.

I also tried passing only this telNumberErrors[telNumberErrorNo] but its showing only one message every time i.e message contained in telNumberErrors[0]

plz help me

Thanks in advance

Uttara
  • 2,406
  • 2
  • 21
  • 35

2 Answers2

8

Well I got the solution to my question so I thought to answer my own question that it may help others

just create a function and return the error which is being alerted

var dispError = function(){
    return telNumberErrors[telNumberErrorNo];
}

and then pass that function as the third argument to addMethod

jQuery.validator.addMethod("UKTelNumber", function(value,element) {    
    if (!checkUKTelephone (value)) {
        return false;
    }
    else {
        return true
    }       
},dispError);

then call the validate method

$(document).ready(function(){
    $("#myform").validate({
        rules:{
            field:{
                required:true;
                UKTelNumber:true
            }
        }       
    });
});
Uttara
  • 2,406
  • 2
  • 21
  • 35
1

Here is my example:

$.validator.addMethod('variable', function (value, element, params) {
    if (!/[a-z]/i.test(value[0])) {
        return this.optional(element) || false;
    } else if (/[~`!#$%\^&*+=\-\[\]\\';.,/(){}|\\":<>\?]/g.test(value)) {
        return this.optional(element) || false;
    } else {
        return this.optional(element) || true;
    }
}, function(error, element) {
    var value = $(element).val();
    if (!/[a-z]/i.test(value[0])) {
        return 'First character must be a letter'
    }
    if (/[~`!#$%\^&*+=\-\[\]\\';.,/(){}|\\":<>\?]/g.test(value)) {
        return 'No special characters except: _'
    }   
})
spitz
  • 598
  • 6
  • 19