Allow numbers and commas in JQuery Validation?

I'm using a jQuery validation-plugin to validate a form's fields. I've got a scenario where we need to validate a field to allow only commas and numbers.

Here's my HTML-code:

<input type="text" placeholder="Number of Employees" required class="form-control" name="employeeno">

And here are the jQuery validation-plugin rules:

    Regex: "[0-9,]+",
    minlength: 1,
    maxlength: 20

jQuery.validator.addMethod("Regex", function(value, element, param) {
    return value.match(new RegExp("." + param + "$"));
}, "Please enter a valid number");

This code actually works if I type at least 2 characters. But if I'm entering only one number - e.g. 2 or 3 - it is displaying an error, allthough I've set my minimum length to one. Why?


Your regex is not correct. . in regex matches any one character, you need to use ^ for start of the line

return value.match(new RegExp("^" + param + "$"));
                               ^^ here

But you can use the pattern rule from the additional methods file

    rules: {
        employeeno: {
            pattern: /^[0-9,]+$/,
            minlength: 1,
            maxlength: 20
    messages: {
        employeeno: {
            pattern: 'Please enter a valid number'

Demo: Fiddle

Need Your Help

Processing array of hashrefs correctly


I have an list of maps in my code.

Form selection handling

jquery forms

I have a product selection page where you choose a plan and once selected it displays the selection information in a div. The problem is if the page gets refreshed the summary div disappears but it

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.