How does JS regular expression judge whether a string contains letters, numbers and special characters?

introduce

In daily life, logins are everywhere.

If you log in, you will have an account and then you will have a password. When we use an APP or a website, we usually require us to log in before we can get related services. Here we specifically point out a certain treasure-you cannot browse, use search, or products without logging in. details page.

introduce

Generally speaking, each APP or website will have strict requirements on the format of the account password.

Then verify the account number and password. Of course, this is the back-end database comparison. This time we mainly talk about the constraints of the previous input— regular expressions :

Here we use passwords as an example. The main reason is that there are too many types of accounts. Some websites support ID login, and some websites only support mobile phone number login, which is complicated.

analyze

Our common passwords are usually divided into three types:

1. Pure numbers

2. Numbers + letters (some banks use this method)

3. Numbers + letters + special characters

All three are introduced here.

1. Pure numbers

This is very simple:

let regNum = /\d+/

\d refers to 0-9, and its function is the same as [0-9].

\d+ means must contain a number.

2. Numbers + letters

 There are many ways to add numbers to letters, but for the sake of understanding, let's take them apart:

let regLet = /[a-zA-Z]{1,n}/

 [a-zA-Z] are actually uppercase and lowercase letters, and the following {1,n} has the same effect as the "+" behind \d.

For convenience, you can also use "+" instead of {1,n} (there is no space in between, please pay attention!!).

let regLet = /[a-zA-Z]+/

3. Numbers + letters + special symbols

As above, we also take it apart and say:

There are many special symbols, so we can only list them one by one:

let regSpe = /[(\ )(\~)(\!)(\@)(\#)(\$)(\%)(\^)(\&)(\*)(\()(\))(\-)(\_)(\+)(\=)(\[)(\])(\{)(\})(\|)(\\)(\;)(\:)(\')(\")(\,)(\.)(\/)(\<)(\>)(\?)(\)]/

Up to now, we can already constrain the content of the input:

We only need to use the judgment statement if-else:

// 判断密码是否包含数字和字母,以及特殊符号
if (!regNum.test(pwd.value) && !regLet.test(pwd.value) && !regSpe.test(pwd.value)) {
    pwdSpan.innerHTML = '格式错误'
}

at last

Of course, we usually also limit the length of the input, usually the password is 6-20 characters:

At this time, we can use:

// 限制长度:
let flagS = pwd.value.length >= 6 ? 1 : 0
let flagL = pwd.value.length <= 20 ? 1 : 0

// 如果长度在6-20中
if (flagS && flagL) {
    // 判断密码是否包含数字和字母,以及特殊符号
    if (!regNum.test(pwd.value) || !regLet.test(pwd.value) || !regSpe.test(pwd.value)) {
        pwdSpan.innerHTML = '格式错误'
        return false
        }
    }

In this way, we can achieve the constraint length while requiring letters and numbers and special symbols.

 

 

You're done. 

Guess you like

Origin blog.csdn.net/m0_54066656/article/details/130641959
Recommended