[英]Javascript validation - Min/Max number of characters AND must contain number
I have the following problem: 我有以下问题:
I need to validate an input (password field) with Javascript / jQuery 我需要使用Javascript / jQuery验证输入(密码字段)
The rules are: 规则是:
it must be 8 to 32 characters it must contain letters AND at least one number 它必须是8到32个字符,必须包含字母和至少一个数字
So my logic is the following but I can't seem to be able to implement it 所以我的逻辑如下,但我似乎无法实现它
be 8 to 32 是8到32
if it's NOT 8 to 32 characters and doesn't have numbers
{
jQuery('#passwordfield').addClass('error');
}
I tried the following (just with 0 as number, for test purposes) 我尝试了以下(出于测试目的,仅将0用作数字)
if(((jQuery('#passwordfield').val().length <= 7) || (jQuery('#passwordfield').val().length >= 33)) && ((jQuery('#passwordfield').val().indexOf("0") == -1)))
{
jQuery('#passwordfield').addClass('error');
}
The problem with the above code is that it returns true if you type enough characters (8 to 32) and NOT contain a number since the first part of the && is true 上面的代码的问题是,如果您键入足够的字符(8到32)并且不包含数字,则返回true,因为&&的第一部分为true
Try this : 尝试这个 :
var p = jQuery('#passwordfield').val();
if(p.length <=7 || p.length >= 33 || !p.match(/\d/) || !p.match(/[a-z]/i))
$('.whatever').addClass('error');
You can use regular expression:- 您可以使用正则表达式:
var val = jQuery('#passwordfield').val();
if(val.length <=7 || val.length >= 33 || !/[0-9]/.test(val) || !/[a-zA-Z]/.test(val))
{
// show error
}
String must contain 0..* letters and 1..* numbers (with a total length of 8..32): 字符串必须包含0 .. *字母和1 .. *数字(总长度为8..32):
if (str.search(/^[a-zA-Z0-9]{8,32}$/) == -1 || str.search(/\d/) == -1) {
jQuery('#passwordfield').addClass('error');
}
String must contain 1..* letters and 1..* numbers (with a total length of 8..32): 字符串必须包含1 .. *个字母和1 .. *个数字(总长度为8..32):
if (str.search(/^[a-zA-Z0-9]{8,32}$/) == -1 || str.search(/[a-zA-Z]\d|\d[a-zA-Z]/) == -1) {
jQuery('#passwordfield').addClass('error');
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.