使用特定规则验证密码的jQuery方法 [英] jQuery method to validate a password with specific rules

查看:108
本文介绍了使用特定规则验证密码的jQuery方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是jquery的新手,正在尝试使用validate的基本复杂密码.

I'm new to jquery and trying to use the validate a password of pretty basic complexity.

密码必须至少包含7个字符,至少1个大写字母,至少1个小写字母和至少1个数字或特殊字符.

The password must be at least 7 characters, have at least 1 upper case, have at least 1 lower case, and at least 1 number OR special character.

这个问题与此答案非常相似,但是我在添加数字或特殊字符"部分.

This question is very similar to this answer I found, however I'm having trouble adding the "digit OR special char" part.

我认为这是我没得到的正则表达式.我对该答案的修改如下:

I think it's a regex I'm just not getting. My modification to that answer looks like this:

$.validator.addMethod("pwcheck", function(value) {
return /^[A-Za-z0-9\d=!\-@._*]*$/.test(value) // consists of only these
   && /[a-z]/.test(value) // has a lowercase letter
   && /[A-Z]/.test(value) //has an uppercase letter
   && (/\d/.test(value) || /~!@#$%^&*_-+=[]\{}|;':",.<> /.test(value)
       // has a digit or special char
});

推荐答案

您需要在最后一个条件上关闭括号.但是我实际上注意到您的正则表达式有几个问题.例如,您需要将所有特殊字符放在一个括号中,以便它不会连续匹配所有这些字符.

You needed to close your parenthesis on your last conditional. But I actually noticed a couple issues with your regex. For one, you need to group all the special characters in a bracket, so it won't match all those characters consecutively.

但是除此之外,正则表达式太冗长了.这是一个更简单的解决方案.

But beyond that, the Regex is way too verbose. Here's a much simpler solution.

$.validator.addMethod("pwcheck", function(value) {
    return /[A-Z]+[a-z]+[\d\W]+/.test(value)
});

这将匹配1个或多个大写字符,1个或多个小写字符以及1个或多个数字/特殊字符.但是,这有一个缺陷.它只会按此特定顺序匹配.这意味着大写字母必须在小写字母之前,小写字母必须在数字之前.它会匹配

This will match 1 or more uppercase characters, 1 or more lowercase characters and 1 or more digit/special character. There's one flaw with this however. It will only match in this particular order. That means the uppercase must come before the lowercase and the lowercase before the digits. It will match things like

AFDSabcd1435

但不是这样的

aA5fdHD14z

要进行更准确的验证,它应该看起来像这样

To have a more accurate validation, it should probably look more like this

$.validator.addMethod("pwcheck", function(value) {
    return /[A-Z]+/.test(value) && /[a-z]+/.test(value) && 
    /[\d\W]+/.test(value) && /\S{7,}/.test(value);
});

这不像我以前的想法那么干净,但是它将传递更多的选择.

This isn't quite as clean as my previous idea, but it will pass more options.

这是一个示例,您可以使用JavaScript函数进行测试.

Here's an example you can test out with a JavaScript function.

function testValue(string) { 
    return /[A-Z]+/.test(string) && /[a-z]+/.test(string) &&
    /[\d\W]/.test(string) && /\S{7,}/.test(string)
}

testValue("aGFbsdf4")
=> true

这篇关于使用特定规则验证密码的jQuery方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆