简体   繁体   中英

RegEx for alphanumeric and some certain special characters

I am trying to allow English alphabets, numeric values and the following characters only:

- # $ % & * ( ) [ ] , . / - _ +

I have managed to come up with the following code

<form id="accountForm" action="">
   <input type="text" name="my_input">
</form>

$(function() {

    $.validator.addMethod("accept", function(value, element, param) {
        return value.match(new RegExp("." + param + "$"));
    }, 'Only English is allowed');        


    $( "#accountForm" ).validate({
        rules: {
            my_input : {
                required: true,
                accept: '[a-zA-Z0-9@%#&()/+*$,._\\-]+$'
            }              

        }
    });
 });

But there are some problems :

  1. If I try to add [ ] the code completely stops working
  2. If I add other characters that or not in the list above, after any alphabets it does not show any error message. Example : ABC你好
  3. If I enter just a letter it gives an error.

Here's a demo of my code: https://jsfiddle.net/w2p1rdbd/1/

Could you please show me how to fix this?

Thank you very much!

I don't see any need for manipulating the regex in the accept method. ( The new RegExp("." + param + "$") ). This will make your regexend up like .[a-zA-Z0-9@%#&()/+*$,._\\\\-]+$$ .

And the start of the line should be anchored with a ^ (matching the start of the string) to disallow foreign characters in the beginning.

I removed the . and $ in your example, added the ^ to the "original" regex (ending up with ^[a-zA-Z0-9@%#&()/+*$,._\\\\-]+$ ) and it appears to be working.

Your code modified:

 $(function() { $.validator.addMethod("accept", function(value, element, param) { return value.match(new RegExp(param)); }, 'Only English is allowed'); $( "#accountForm" ).validate({ rules: { my_input : { required: true, accept: '^[a-zA-Z0-9@%#&()/+*$,._\\\\-]+$' } } }); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.16.0/jquery.validate.min.js"></script> <form id="accountForm" action=""> <input type="text" name="my_input"> </form> 

First of all, note that JavaScript has a regular expression type, so regular expressions can be specified as a language element do not need to be specified as a string, which does save you a couple of escape sequences and also your syntax highlighting can help you better.

Then you are doing this_

"." + param + "$"

This will change your regular expression. The dot means that an additional character of any class is matched at the beginning. Hence a single character won't match at all, you'll need to characters to match and the second charachter must be of the class you specified. Then you also append the $ at the end. You also have that character in your original expression: '[a-zA-Z0-9@%#&()/+*$,._\\\\-]+$' , so now you got it twice. However one of them is ignored, so while this is not helpful, it is no harm. Probably you meant to use "^" + param + "$" , because that would mean "match from the beginning ( ^ ) to the end ( $ ), but then you should not include these in both your variable expression and your function.

Then there is the issue of the [] . You simply need to escape them in the regex. But you ALSO need to escape them for the string, and then you need to escape the regex escape sequence for the string. So quite a lot of escapes. Note also that this applies to the dash, but the problem with the dash is ignores as long as it is the last part of the [] sequence. So finally your regex needs to be "^[a-zA-Z0-9@%#&()/+*$,._\\\\-\\\\[\\\\]]+$" . (The escape for the opening [ is optional)

However if you use a literal, then you can just write /^[a-zA-Z0-9@%#&()/+*$,._\\-\\[\\]]+$/ , which is less escape sequences. In total that would be the result:

$(function() {
    $.validator.addMethod("accept", function(value, element, param) {
        return param.test(value);
    }, 'Only English is allowed');        


    $( "#accountForm" ).validate({
        rules: {
            my_input : {
                required: true,
                accept: /^[a-zA-Z0-9@%#&()/+*$,._\-\[\]]+$/
            }
        }
    });
});

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