简体   繁体   中英

javascript regex to require at least one special character

I've seen plenty of regex examples that will not allow any special characters. I need one that requires at least one special character.

I'm looking at a C# regex

var regexItem = new Regex("^[a-zA-Z0-9 ]*$");

Can this be converted to use with javascript? Do I need to escape any of the characters?

Based an example I have built this so far:

var regex = "^[a-zA-Z0-9 ]*$";

//Must have one special character
if (regex.exec(resetPassword)) {
    isValid = false;
    $('#vsResetPassword').append('Password must contain at least 1 special character.');
}

Can someone please identify my error, or guide me down a more efficient path? The error I'm currently getting is that regex has no 'exec' method

In javascript, regexs are formatted like this:

/^[a-zA-Z0-9 ]*$/

Note that there are no quotation marks and instead you use forward slashes at the beginning and end.

Your problem is that "^[a-zA-Z0-9 ]*$" is a string, and you need a regex:

var regex = /^[a-zA-Z0-9 ]*$/;                 // one way
var regex = new RegExp("^[a-zA-Z0-9 ]*$");     // another way

[ more information ]

Other than that, your code looks fine.

In javascript, you can create a regular expression object two ways.

1) You can use the constructor method with the RegExp object (note the different spelling than what you were using):

var regexItem = new RegExp("^[a-zA-Z0-9 ]*$");

2) You can use the literal syntax built into the language:

var regexItem = /^[a-zA-Z0-9 ]*$/;

The advantage of the second is that you only have to escape a forward slash, you don't have to worry about quotes. The advantage of the first is that you can programmatically construct a string from various parts and then pass it to the RegExp constructor.


Further, the optional flags for the regular expression are passed like this in the two forms:

var regexItem = new RegExp("^[A-Z0-9 ]*$", "i");
var regexItem = /^[A-Z0-9 ]*$/i;

In javascript, it seems to be a more common convention to the user /regex/ method that is built into the parser unless you are dynamically constructing a string or the flags.

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