Search code examples
jqueryregexjquery-validate

Regex not working in jquery validation plugin


I am using below code

$(function() {
    $("#myForm").validate({
        rules: {
            experience: {
                required: true,
                regex: '^[0-9]$'
            }
        },
        messages: {
            experience: {
                required: "Please provide experience",
                regex: "Provide a valid input for experience"
            }
        }
    });
});

But the above code is not taking 2 or 22 as valid input? What I am doing wrong? Help required...


Solution

  • Try this regex instead:

    ^[0-9]+$
    

    Then put it in the code:

    $(function() {
       $.validator.addMethod("regex", function(value, element, regexpr) {          
         return regexpr.test(value);
       }, "Please enter a valid pasword.");    
    
       $("#myForm").validate({
           rules: {
               experience: {
                   required: true,
                   regex: /^[0-9]+$/
               }
           }
       });
    });
    

    Here is a working demo:

    http://jsfiddle.net/4PuJL/1/