简体   繁体   English

Javascript 具有特殊字符的正则表达式密码验证

[英]Javascript regular expression password validation having special characters

I am trying to validate the password using regular expression.我正在尝试使用正则表达式验证密码。 The password is getting updated if we have all the characters as alphabets.如果我们将所有字符都作为字母,则密码会更新。 Where am i going wrong?我哪里错了? is the regular expression right?正则表达式对吗?

function validatePassword() {
    var newPassword = document.getElementById('changePasswordForm').newPassword.value;
    var minNumberofChars = 6;
    var maxNumberofChars = 16;
    var regularExpression  = /^[a-zA-Z0-9!@#$%^&*]{6,16}$/;
    alert(newPassword); 
    if(newPassword.length < minNumberofChars || newPassword.length > maxNumberofChars){
        return false;
    }
    if(!regularExpression.test(newPassword)) {
        alert("password should contain atleast one number and one special character");
        return false;
    }
}

Use positive lookahead assertions:使用积极的前瞻断言:

var regularExpression = /^(?=.*[0-9])(?=.*[!@#$%^&*])[a-zA-Z0-9!@#$%^&*]{6,16}$/;

Without it, your current regex only matches that you have 6 to 16 valid characters, it doesn't validate that it has at least a number, and at least a special character.没有它,您当前的正则表达式只匹配您有 6 到 16 个有效字符,它不会验证它至少有一个数字,至少有一个特殊字符。 That's what the lookahead above is for.这就是上面的前瞻。

  • (?=.*[0-9]) - Assert a string has at least one number; (?=.*[0-9]) - 断言一个字符串至少有一个数字;
  • (?=.*[!@#$%^&*]) - Assert a string has at least one special character. (?=.*[!@#$%^&*]) - 断言一个字符串至少有一个特殊字符。
function validatePassword() {
    var p = document.getElementById('newPassword').value,
        errors = [];
    if (p.length < 8) {
        errors.push("Your password must be at least 8 characters"); 
    }
    if (p.search(/[a-z]/i) < 0) {
        errors.push("Your password must contain at least one letter.");
    }
    if (p.search(/[0-9]/) < 0) {
        errors.push("Your password must contain at least one digit."); 
    }
    if (errors.length > 0) {
        alert(errors.join("\n"));
        return false;
    }
    return true;
}

There is a certain issue in below answer as it is not checking whole string due to absence of [ ] while checking the characters and numerals, this is correct version以下答案存在某个问题,因为在检查字符和数字时由于缺少 [ ] 而没有检查整个字符串,这是正确的版本

I use the following script for min 8 letter password, with at least a symbol, upper and lower case letters and a number我使用以下脚本输入最少 8 个字母的密码,至少包含一个符号、大小写字母和一个数字

function checkPassword(str)
{
    var re = /^(?=.*\d)(?=.*[!@#$%^&*])(?=.*[a-z])(?=.*[A-Z]).{8,}$/;
    return re.test(str);
}

you can make your own regular expression for javascript validation您可以为javascript验证制作自己的正则表达式

    /^            : Start
    (?=.{8,})        : Length
    (?=.*[a-zA-Z])   : Letters
    (?=.*\d)         : Digits
    (?=.*[!#$%&? "]) : Special characters
    $/              : End



        (/^
        (?=.*\d)                //should contain at least one digit
        (?=.*[a-z])             //should contain at least one lower case
        (?=.*[A-Z])             //should contain at least one upper case
        [a-zA-Z0-9]{8,}         //should contain at least 8 from the mentioned characters

        $/)

Example:-   /^(?=.*\d)(?=.*[a-zA-Z])[a-zA-Z0-9]{7,}$/

Don't try and do too much in one step.不要试图一步做太多。 Keep each rule separate.将每个规则分开。

function validatePassword() {
    var p = document.getElementById('newPassword').value,
        errors = [];
    if (p.length < 8) {
        errors.push("Your password must be at least 8 characters");
    }
    if (p.search(/[a-z]/i) < 0) {
        errors.push("Your password must contain at least one letter."); 
    }
    if (p.search(/[0-9]/) < 0) {
        errors.push("Your password must contain at least one digit.");
    }
    if (errors.length > 0) {
        alert(errors.join("\n"));
        return false;
    }
    return true;
}

Regex for password :密码正则表达式

/^(?=.*\\d)(?=.*[AZ])(?=.*[az])(?=.*[a-zA-Z!#$%&? "])[a-zA-Z0-9!#$%&?]{8,20}$/

Took me a while to figure out the restrictions, but I did it!我花了一段时间才弄清楚这些限制,但我做到了!

Restrictions: (Note: I have used >> and << to show the important characters)限制:(注意:我使用了>><<来显示重要的字符)

  1. Minimum 8 characters {>>8,20}最少 8 个字符{>>8,20}
  2. Maximum 20 characters {8,>>20}最多 20 个字符{8,>>20}
  3. At least one uppercase character (?=.*[AZ])至少一个大写字符(?=.*[AZ])
  4. At least one lowercase character (?=.*[az])至少一个小写字符(?=.*[az])
  5. At least one digit (?=.*\\d)至少一位(?=.*\\d)
  6. At least one special character (?=.*[a-zA-Z >>!#$%&? "<<])[a-zA-Z0-9 >>!#$%&?<< ]至少一个特殊字符(?=.*[a-zA-Z >>!#$%&? "<<])[a-zA-Z0-9 >>!#$%&?<< ]
<div>
    <input type="password" id="password" onkeyup="CheckPassword(this)" />
</div>   

<div  id="passwordValidation" style="color:red" >
    
</div>

 function CheckPassword(inputtxt) 
    { 
    var passw= /^(?=.*\d)(?=.*[a-z])(?=.*[^a-zA-Z0-9])(?!.*\s).{7,15}$/;
    if(inputtxt.value.match(passw)) 
    { 
    $("#passwordValidation").html("")
    return true;
    }
    else
    { 
    $("#passwordValidation").html("min 8 characters which contain at least one numeric digit and a special character");
    return false;
    }
    }

it,s work perfect for me and i am sure will work for you guys checkout it easy and accurate它对我来说很完美,我相信你们会很容易和准确地结帐

var regix = new RegExp("^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[!@#\$%\^&\*])(?=. 
            {8,})");

if(regix.test(password) == false ) {
     $('.messageBox').html(`<div class="messageStackError">
       password must be a minimum of 8 characters including number, Upper, Lower And 
       one special character
     </div>`);
}
else
{
        $('form').submit();
}

If you check the length seperately, you can do the following:如果单独检查长度,您可以执行以下操作:

var regularExpression  = /^[a-zA-Z]$/;

if (regularExpression.test(newPassword)) {
    alert("password should contain atleast one number and one special character");
    return false;
} 

After a lot of research, I was able to come up with this.经过大量研究,我能够想出这个。 This has more special characters这有更多特殊字符

validatePassword(password) {
        const re = /(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[!@#$%^&*()+=-\?;,./{}|\":<>\[\]\\\' ~_]).{8,}/
        return re.test(password);
    }

Very helpful.很有帮助。 It will help end user to identify which char is missing\/required while entering password.它将帮助最终用户在输入密码时识别缺少\/需要的字符。

Here is some improvement, ( here u could add your required special chars.)这是一些改进,(在这里你可以添加你需要的特殊字符。)

function validatePassword(p) {
    //var p = document.getElementById('newPassword').value,
    const errors = [];
    if (p.length < 8) {
        errors.push("Your password must be at least 8 characters");
    }
    if (p.length > 32) {
        errors.push("Your password must be at max 32 characters");
    }
    if (p.search(/[a-z]/) < 0) {
        errors.push("Your password must contain at least one lower case letter."); 
    }
    if (p.search(/[A-Z]/) < 0) {
        errors.push("Your password must contain at least one upper case letter."); 
    }

    if (p.search(/[0-9]/) < 0) {
        errors.push("Your password must contain at least one digit.");
    }
   if (p.search(/[!@#\$%\^&\*_]/) < 0) {
        errors.push("Your password must contain at least special char from -[ ! @ # $ % ^ & * _ ]"); 
    }
    if (errors.length > 0) {
        console.log(errors.join("\n"));
        return false;
    }
    return true;
}

我的验证 shema - 大写、小写、数字和特殊字符

new RegExp("^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[^A-Za-z0-9_])")

当您重新创建帐户密码时,请确保它是 8-20 个字符,包括数字和特殊字符,例如##\\/* - 然后验证新密码并重新输入完​​全相同的密码,应该可以解决密码验证的问题

Here is the password validation example I hope you like it.这是密码验证示例,希望您喜欢。

Password validation with Uppercase, Lowercase, special character,number and limit 8 must be required.必须使用大写、小写、特殊字符、数字和限制 8 的密码验证。

 function validatePassword(){ var InputValue = $("#password").val(); var regex = new RegExp("^(?=.*[az])(?=.*[AZ])(?=.*[0-9])(?=.*[!@#\\$%\\^&\\*])(?=.{8,})"); $("#passwordText").text(`Password value:- ${InputValue}`); if(!regex.test(InputValue)) { $("#error").text("Invalid Password"); } else{ $("#error").text(""); } }
 #password_Validation{ background-color:aliceblue; padding:50px; border:1px solid; border-radius:5px; } #passwordText{ color:green; } #error{ color:red; } #password{ margin-bottom:5px; }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div id="password_Validation"> <h4>Password validation with Uppercase Lowercase special character and number must be required.</h4> <div> <input type="password" name="password" id="password"> <button type="button" onClick="validatePassword()">Submit</button> <div> <br/> <span id="passwordText"></span> <br/> <br/> <span id="error"></span> <div>

Here I'm extending @João Silva's answer.在这里,我正在扩展@João Silva 的答案。 I had a requirement to check different parameters and throw different messages accordingly.我需要检查不同的参数并相应地抛出不同的消息。

I divided the regex into different parts and now the checkPasswordValidity(String)<\/code> function checks each regex part conditionally and throw different messages.我将正则表达式分成不同的部分,现在checkPasswordValidity(String)<\/code>函数有条件地检查每个正则表达式部分并抛出不同的消息。

Hope the below example will help you to understand better!希望下面的例子能帮助你更好地理解!

 \/** * @param {string} value: passwordValue *\/ const checkPasswordValidity = (value) => { const isNonWhiteSpace = \/^\\S*$\/; if (!isNonWhiteSpace.test(value)) { return "Password must not contain Whitespaces."; } const isContainsUppercase = \/^(?=.*[AZ]).*$\/; if (!isContainsUppercase.test(value)) { return "Password must have at least one Uppercase Character."; } const isContainsLowercase = \/^(?=.*[az]).*$\/; if (!isContainsLowercase.test(value)) { return "Password must have at least one Lowercase Character."; } const isContainsNumber = \/^(?=.*[0-9]).*$\/; if (!isContainsNumber.test(value)) { return "Password must contain at least one Digit."; } const isContainsSymbol = \/^(?=.*[~`!@#$%^&*()--+={}\\[\\]|\\\\:;"'<>,.?\/_₹]).*$\/; if (!isContainsSymbol.test(value)) { return "Password must contain at least one Special Symbol."; } const isValidLength = \/^.{10,16}$\/; if (!isValidLength.test(value)) { return "Password must be 10-16 Characters Long."; } return null; } \/\/------------------ \/\/ Usage\/Example: let yourPassword = "yourPassword123"; const message = checkPasswordValidity(yourPassword); if (!message) { console.log("Hurray! Your Password is Valid and Strong."); } else { console.log(message); }<\/code><\/pre>

Also, we can combine all these regex patterns into single regex:此外,我们可以将所有这些正则表达式模式组合成一个正则表达式:

 let regularExpression = \/^(\\S)(?=.*[0-9])(?=.*[AZ])(?=.*[az])(?=.*[~`!@#$%^&*()--+={}\\[\\]|\\\\:;"'<>,.?\/_₹])[a-zA-Z0-9~`!@#$%^&*()--+={}\\[\\]|\\\\:;"'<>,.?\/_₹]{10,16}$\/;<\/code><\/pre>

Note:<\/strong> The regex discussed above will check following patterns in the given input value\/password:注意:<\/strong>上面讨论的正则表达式将检查给定输入值\/密码中的以下模式:

  • It must not contain any whitespace.它不能包含任何空格。<\/li>
  • It must contain at least one uppercase, one lowercase and one digit character.它必须至少包含一个大写字母、一个小写字母和一个数字字符。<\/li>
  • It must contain at least one special character.它必须至少包含一个特殊字符。 [~`!@#$%^&*()--+={}[]|\\:;"'<>,.?\/_₹] [~`!@#$%^&*()--+={}[]|\\:;"'<>,.?\/_₹]<\/li>
  • Length must be between 10 to 16 characters.长度必须介于 10 到 16 个字符之间。<\/li><\/ul>

    Thanks!谢谢!

    "

International UTF-8国际 UTF-8

None of the solutions here allows international characters, ie éÉáÁöÖæÆþÞóÓúÚ, but are only focused on the english alphabet.这里没有一个解决方案允许使用国际字符,即 éÉáÁöÖæÆþÞóÓúÚ,但只关注英文字母。

The following regEx uses unicode, UTF-8, to recognise upper and lower case and thus, allow international characters:以下正则表达式使用 unicode UTF-8 来识别大小写,因此允许使用国际字符:

// Match uppercase, lowercase, digit or #$!%*?& and make sure the length is 8 to 96 in length  
const pwdFilter = /^(?=.*\p{Ll})(?=.*\p{Lu})(?=.*[\d|@#$!%*?&])[\p{L}\d@#$!%*?&]{8,96}$/gmu

if (!pwdFilter.test(pwd)) {
    // Show error that password has to be adjusted to match criteria
}

This regEx这个正则表达式

/^(?=.*\\p{Ll})(?=.*\\p{Lu})(?=.*[\\d|@#$!%*?&])[\\p{L}\\d@#$!%*?&]{8,96}$/gmu

checks if an uppercase, lowercase, digit or #$!%*?& are used in the password.检查密码中是否使用了大写、小写、数字或#$!%*?&。 It also limits the length to be 8 minimum and maximum 96, the length of 😀🇮🇸🧑‍💻 emojis count as more than one character in the length.它还将长度限制为最小 8 和最大 96,😀🇮🇸🧑‍💻 emojis 的长度在长度中算作多个字符。 The u in the end, tells it to use UTF-8.最后的u告诉它使用 UTF-8。

var regularExpression = /^(?=. [0-9])(?=. [!@#$%^& ])[a-zA-Z0-9!@#$%^& ]{6,16}$/; var regularExpression = /^(?=. [0-9])(?=. [!@#$%^& ])[a-zA-Z0-9!@#$%^& ]{6,16} $/;

Without it, your current regex only matches that you have 6 to 16 valid characters, it doesn't validate that it has at least a number, and at least a special character.没有它,您当前的正则表达式只匹配您有 6 到 16 个有效字符,它不会验证它至少有一个数字,至少有一个特殊字符。 That's what the lookahead above is for.这就是上面的前瞻性的目的。

(?=. [0-9]) - Assert a string has at least one number; (?=. [0-9]) - 断言一个字符串至少有一个数字; (?=. [.@#$%^&*]) - Assert a string has at least one special character. (?=. [.@#$%^&*]) - 断言一个字符串至少有一个特殊字符。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM