Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
925 views
in Technique[技术] by (71.8m points)

regex - jQuery Validate method checking for special characters

I am trying (and failing) to write a regular expression statement that checks for special characters such as !@#$%^&*()_+<>?'"{}[] in my Javascript form validation.

I understand that this has probably been asked 1000 times but i'm under some serious time pressure. If you would rather not answer the question below and you are able to point me in the direction of a previous answer to the above question I would greatly appreciate it.

On a similar note, can anyone tell me why the following is shooting an error when I enter lowercase 'abc', etc? I'm baffled.

jQuery.validator.addMethod("specialChars", function( value, element ) {
        var regex = new RegExp("^[a-zA-Z0-9]+$");
        var key = String.fromCharCode(event.charCode ? event.which : event.charCode);

        if (!regex.test(key)) {
           event.preventDefault();
           return false;
        }
    }, "please use only alphanumeric or alphabetic characters");
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Instead of writing your own custom method from scratch, include the additional-methods.js file and use the alphanumeric rule.

$(document).ready(function () {

    $('#myform').validate({
        rules: {
            field: {
                alphanumeric: true
            }
        }
    });

});

Demo: http://jsfiddle.net/YsAKx/


If you don't want to include an additional external file, simply copy the default alphanumeric method out of it...

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...