Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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...

like image 855
Anubhav Avatar asked Jan 06 '14 09:01

Anubhav


2 Answers

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/

like image 100
Stephan Avatar answered Sep 27 '22 18:09

Stephan


There is no regex method in validate jquery: You have to create of your regex method of your own

You need to use addmethod

$.validator.addMethod("regx", function(value, element, regexpr) {          
    return regexpr.test(value);
}, "Provide a valid input for experience.");

Your function here:

$(function() {
    $("#myForm").validate({
        rules: {
            experience: {
                required: true,
                regex: /^[0-9]$/
            }
        },
        messages: {
            experience: {
                required: "Please provide experience",

            }
        }
    });
});

add regex in Jquery.validate

like image 42
Somnath Kharat Avatar answered Sep 27 '22 19:09

Somnath Kharat