jQuery Validate method checking for special characters

▼魔方 西西 提交于 2019-12-18 02:58:24

问题


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");

回答1:


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");



回答2:


Few changes

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

        if (!regex.test(key)) {
           return false;
        }
        return true;
    }, "please use only alphanumeric or alphabetic characters");
  1. You need to return the value true, if the test is valid
  2. The validator is not a event handler so you cannot use event.preventDefault(), this has to be done in the keypress event.
  3. You need to test the value passed to the validate method.

Demo: Fiddle

Note: Since you are using + wild char at least one character is required in the text box, you may want to split it into two rules using the required rule and change the wild char to *.




回答3:


^[a-zA-Z0-9;,.!@#$%:{}[]?"^&*()/\']*|[^&;<>\`]*

you want special charecter add here in this [] braces ^[a-zA-Z0-9;,.!@#$%:{}[]?"^&*()/\'] and you dont want then add here this part [^&;<>\]`



来源:https://stackoverflow.com/questions/14949257/jquery-validate-method-checking-for-special-characters

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!