js simple form validation

This example involves only a temporary form of judgment empty, if the contents of the form is empty prompt information, the mailbox is not formatted correctly also gives tips. Late and then continue to improve the form of validation.

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title></title>
	</head>
	<body>
		
		<form action="#"  id="register" onsubmit="return check(this)">
			用户名:<input type="text" name="user" id="user" value="" /><br />
			密码:<input type="password" name="password" id="password" value="" /><br />
			
			邮箱:<input type="text" name="email" id="email" value="" /><br />
			
			<input type="submit" value="提交"/>
		</form>
		
		<script type="text/javascript">

            //为字符串增加 trim 方法,使用正则表达式截取空格
			String.prototype.trim = function(){
				return this.replace(/^s*/,"").replace(/\s*$/,"");
			}

			//负责处理表单 submit 事件的函数
			var check = function(){
				//访问页面中的第一个表单
				var form = document.forms[0];
                //错误字符串
				var errStr = '';
                //当用户名为空时
				if(form.user.value == null || form.user.value.trim() ==""){
					errStr += "\n 用户名不能为空。!";
					form.user.focus();
				}
                //当密码为空时
				if(form.password.value == null || form.password.value.trim() ==""){
					errStr += "\n 密码不能为空。!";
					form.password.focus();
				}
                //当邮件为空时
				if(form.email.value == null || form.email.value.trim() ==""){
					errStr += "\n 邮箱不能为空。!";
					form.email.focus();
				}
				//使用正则表达式校验邮箱的格式是否正确
				if(!/^\w +([-+.]\w+)*@\w+([-+.]\w+)*\.\w+([-+.]\w+)*$/
					.test(form.email.value.trim()))
				{
					errStr += "\n电子邮件格式不正确";
					form.email.focus();
				}
				//如果错误字符串不为空,则表明校验出错
				if(errStr != ""){
                    //弹出错误信息
					alert(errStr);
                    //返回 false ,用于阻止表单提价
					return false;
				}
			}
			
		</script>
	</body>
</html>

 

Guess you like

Origin blog.csdn.net/qq_34851243/article/details/90341905