简体   繁体   中英

Jquery validate plugin alphanumeric method with acceptance of dot

I have a requirement in a username field where I have to validate the special characters but allow '.' dot character. We have custom method in plugin alphanumeric but it doesn't allow dot. please check the fiddle

jQuery.validator.addMethod("alphanumeric", function(value, element) {
    return this.optional(element) || /^\w+$/i.test(value);
}, "Letters, numbers, and . only please");

Use this regex /^[\\w.]+$/i

You can use character set [] of regex to select multiple character.

^ in regex means it starts matching from the start of the string.

\\w in regex means it accepts all alpha Numeric (A-Za-z0-9) and underscore (_).

I have added . inside the character set to allow character . also.

You can add more character inside the [] character set to allow them too.

+ in the regex means it will keep on matching all the character in the string.

$ in regex means it will check till the end of the line if its multi-line

i in regex is a flag that says its case insensitive.

Here is the updated fiddle

http://jsfiddle.net/YsAKx/330/

Updated JS

$(document).ready(function () {

jQuery.validator.addMethod("alphanumeric", function(value, element) {
    return this.optional(element) || /^[\w.]+$/i.test(value);
}, "Letters, numbers, and underscores only please");

    $('#myform').validate({ // initialize the plugin
        rules: {
            field: {
                required: true,
                alphanumeric: true
            }
        },
        submitHandler: function (form) { // for demo
            alert('valid form submitted'); // for demo
            return false; // for demo
        }
    });

});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM