正则表达式验证表单

//使用正则表达式截取空格
	function trim(s)
	{
	return s.replace(/^\s*/,"").replace(/\s*$/,"");
	}
	//表单验证
	function check()
	{
	var form=document.forms[0];
	//错误字符串
	var errStr = "";
	//当用户名为空
	if (trim(form.user.value) == null || trim(form.user.value) == "")
	{
		errStr += "\n用户名不能为空!";
		form.user.focus();
	}
	//当密码为空
	if (trim(form.pass.value) == null || trim(form.pass.value) == "")
	{
		errStr += "\n密码不能为空!";
		form.pass.focus();
	}
	//当电子邮件为空
	if (trim(form.email.value) == null || trim(form.email.value) == "")
	{
		errStr += "\n电子邮件不能为空!";
		form.email.focus();
	}
	//使用正则表达式校验电子邮件的格式是否正确
	if(!/^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/.test(trim(form.email.value)))
	{
		errStr += "\n电子邮件的格式不正确!";
		form.email.focus();
	}
	
		//若是错误字符串不为空,代表校验出错
	if( errStr != "" )
	{
		//弹出出错信息
		alert(errStr);
		//返回false,用于阻止表单提交
		return false;
	}
	}

HTML html

<div align="center">
<form method="post" onsubmit="return check();" 
	name="register" action="http://www.crazyit.org">
	用户名:<input type="text" name="user" /><br />
	密&nbsp;&nbsp;码:<input type="password" name="pass" /><br />
	电&nbsp;&nbsp;邮:<input type="text" name="email" /><br />
	<input type="submit" value="提交" />
</form>
</div>
相关文章
相关标签/搜索