在JavaScript中验证输入的电子邮件和密码

时间:2011-11-24 21:27:10

标签: javascript regex email

我想要做的是在JavaScript中建立一个功能,验证输入的电子邮件和密码,检查输入的电子邮件,确保它在字符串的最后一个句点之后至少有2-3个字符(对于.com) ,.org,.ca等)并且该字符串中至少有一个“@”符号。

至于检查密码,我希望函数检查它至少有一个小写和一个大写字母,至少一个数字,以及至少一个特殊字符(!,@,#,$,%,^ ,&安培;,*,〜)

有没有人知道我需要做些什么才能让正则表达式检查至少1个特殊字符的密码,如!,@,*等?

这就是我所拥有的:

function validatePassword(password)
{
    var passwordPattern = /(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{6,}/;
return passwordPattern.test(password)
}

// Validate form
function validate()
{
var email = user.email.value;
if(validateEmail(user.email.value))
    user.validEmail.value = "OK";
else
    user.validEmail.value = "X";
if(validatePassword(user.password.value))
    user.validPassword.text = "OK";
else
    user.validPassword.text = "X";
}

3 个答案:

答案 0 :(得分:2)

您可以为这两种情况使用正则表达式。 至于电子邮件,你可以在这里阅读更多内容:http://www.zparacha.com/validate-email-address-using-javascript-regular-expression/ 至于密码检查,我建议您阅读:http://www.the-art-of-web.com/javascript/validate-password/

这是验证密码:

<input type="password" id="txtPassword" onblur="validate"/>
<script type="text/javascript" src="../jQuery/jquery-1.6.4.min.js"></script>
<script type="text/javascript">
    var txtPassword = null;

    var txtPassword_Blur = function(e) {
        var exp = /(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{6,}/;
        var validPassword = exp.test($(this).val());
        if(validPassword) {
           alert('valid');
        } else {
           alert('not valid');
        }
    };

    $(function() {
        txtPassword = $("#txtPassword");
        txtPassword.bind("blur", null, txtPassword_Blur);
    });
</script>

注意:此正则表达式不检查特殊字符。我认为这是您的定义所特有的,但您可以编辑表达式并添加您认为特殊的字符列表。

答案 1 :(得分:1)

请使用JavaScript语言{$ 3}}查看我的网页上文本输入元素值的跨浏览器过滤器项目。您可以将值过滤为整数,浮点数或写入自定义过滤器,例如电话号码过滤器。查看输入电子邮件和密码代码的示例:

<!doctype html>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
    <title>Input Key Filter Test</title>
	<meta name="author" content="Andrej Hristoliubov anhr@mail.ru">
	<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
	
	<!-- For compatibility of IE browser with audio element in the beep() function.
	https://www.modern.ie/en-us/performance/how-to-use-x-ua-compatible -->
	<meta http-equiv="X-UA-Compatible" content="IE=9"/>
	
	<link rel="stylesheet" href="https://rawgit.com/anhr/InputKeyFilter/master/InputKeyFilter.css" type="text/css">		
	<script type="text/javascript" src="https://rawgit.com/anhr/InputKeyFilter/master/Common.js"></script>
	<script type="text/javascript" src="https://rawgit.com/anhr/InputKeyFilter/master/InputKeyFilter.js"></script>
	
</head>
<body>
Email: <input type="email" id="Email" value="username@domain.com"/>
<script>
	CreateEmailFilter("Email", function(event){//onChange event
			inputKeyFilter.RemoveMyTooltip();
			var elementNewInteger = document.getElementById("NewEmail");
			elementNewInteger.innerHTML = this.value;
		}
		
		//onblur event. Use this function if you want set focus to the input element again if input value is NaN. (empty or invalid)
		, function(event){ this.ikf.customFilter(this); }
	);
</script>
 New email: <span id="NewEmail"></span>
<hr>
Password: 
<input type="password" id="Password"
	onchange="javascript: onChangePassword(this)"
	onblur="javascript: this.ikf.customFilter(this)"
/>
<script>
	function onChangePassword(input){
		inputKeyFilter.RemoveMyTooltip();
		if(!input.ikf.customFilter(input))
			return false;
		var elementNewPassword = document.getElementById("NewPassword");
		elementNewPassword.innerHTML = input.value;
	}
	CreatePasswordFilter("Password"
		, function(elementInput, value){//customFilter
//consoleLog("password customFilter. elementInput = " + elementInput + "\n\n" + printStackTrace().join("nn"));

				if(typeof value == 'undefined')
					value = elementInput.value;
					
				var array = value.match(/([^a-zA-Z\d]+)/);
				if(array != null){
					inputKeyFilter.TextAdd(isRussian() ?
							"Недопустимый символ: " + array[0]
							: "Invalid symbol: " + array[0]
						, elementInput, "uparrowdivred");
					inputKeyFilter.focus(elementInput);
					return false;
				}
				var passwordLengthMin = 6;
				if(value.length < passwordLengthMin){
					inputKeyFilter.TextAdd(isRussian() ?
							"Пароль должен быть длиннее " + passwordLengthMin + " символов."
							: "The password at least " + passwordLengthMin + " characters."
						, elementInput);
					inputKeyFilter.focus(elementInput);
					return false;
				}
				if(value.match(/(\d+)/i) == null){
					inputKeyFilter.TextAdd(isRussian() ?
							"Введите хотя бы одну цифру."
							: "The password must contain at least one digit."
						, elementInput, "uparrowdivyellow");
					inputKeyFilter.focus(elementInput);
					return false;
				}
				if(value.match(/([a-z]+)/) == null){
					inputKeyFilter.TextAdd(isRussian() ?
							"Введите хотя бы одну латинскую букву."
							: "The password must contain at least one letter."
						, elementInput, "uparrowdivyellow");
					inputKeyFilter.focus(elementInput);
					return false;
				}
				if(value.match(/([A-Z]+)/) == null){
					inputKeyFilter.TextAdd(isRussian() ?
							"Введите хотя бы одну заглавную латинскую букву."
							: "The password must contain at least one upper-case letter."
						, elementInput, "uparrowdivyellow");
					inputKeyFilter.focus(elementInput);
					return false;
				}
				return true;
			}
/*				
		//, null//onChange
		, function(event){//onChange
				input = this;
				inputKeyFilter.RemoveMyTooltip();
				if(!input.ikf.customFilter(input))
					return false;
				var elementNewPassword = document.getElementById("NewPassword");
				elementNewPassword.innerHTML = input.value;
			}
		//, null//onblur
		, function(event){//onblur
				this.ikf.customFilter(this);
			}
*/				
	);
</script>
 New password: <span id="NewPassword"></span>

</body>
</html>

另见我的页面Input Key Filter

答案 2 :(得分:0)

您可以将regexp用于这两个

function validate(form_id,email) {

   var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
   var address = document.forms[form_id].elements[email].value;
   if(reg.test(address) == false) {

      alert('Invalid Email Address');
      return false;
   }
}

发送电子邮件(来源:http://www.white-hat-web-design.co.uk/blog/javascript-validation/

使用相同的方法验证您的密码。

http://www.w3schools.com/jsref/jsref_regexp_test.asp