2

How to use addmethod in jquery.validate. Example

$("#formname").validate({
    rules: {
        textbox: {
            required: true,
            regexp: /['"]/
        },
        methods: {
            required: "Should not be blank",
            regexp: "Single quotes and double quotes not allowed"
        }
    }
});

I need to check this quotes in textbox with addmethod. How can i do this. Explain me by implementing your answer with my sample code.

2 Answers 2

2

First we need a few fixes, the layout for messages is like this (you can't do this with your original options...the plugin just doesn't look for that structure):

$("#formname").validate({
    rules: {
        textbox: {
            required: true,
            regexp: /['"]/
        }
    },
    messages: {
        textbox: {
            required: "Should not be blank",
            regexp: "Single quotes and double quotes not allowed"
        }
    }
});

Then your method would look like this:

$.validator.addMethod("regexp", function(value, element, param) { 
  return this.optional(element) || !param.test(value); 
});

You can test it out here....but you notice your regex is backwards, so the naming's not quite right...I'd rename regexp to nomatch...or something more indicative of the behavior you're looking for.

Sign up to request clarification or add additional context in comments.

Comments

0
$("#formname").validate({
  rules: {
    textbox: {
        required: true,
        regexp: true
    }
  },
  messages: {
     textbox: {
         required: "Should not be blank",
         regexp: "Single quotes and double quotes not allowed"
     }
  }
});



// Regexp validation
$.validator.addMethod("regexp", function(value, element, arg){
var reg_val=$('#textbox').val();
var regExp=/^['"]+$/;

if($('#textbox').val().match(reg_val)){
  return true;
}else{
   return false;
}
}, "");

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.