javascript表单验证

JavaScript024

javascript表单验证,第1张

验证函数如下:

function chkfrm(o){

if(!/\d+/gi.test(o.empid.value)){

alert('雇员编号:只能是数字。')

return false

}

if(o.empname.value==''){

alert('雇员姓名:不能为空。')

return false

}

if(o.empjob.value==''){

alert('雇员工作:不能为空。')

return false

}

if(!/^((((1[6-9]|[2-9]\d)\d{2})[-\/](0?[13578]|1[02])[-\/](0?[1-9]|[12]\d|3[01]))|(((1[6-9]|[2-9]\d)\d{2})[-\/](0?[13456789]|1[012])[-\/](0?[1-9]|[12]\d|30))|(((1[6-9]|[2-9]\d)\d{2})[-\/]0?2[-\/](0?[1-9]|1\d|2[0-8]))|(((1[6-9]|[2-9]\d)(0[48]|[2468][048]|[13579][26])|((16|[2468][048]|[3579][26])00))[-\/]0?2[-\/]29[-\/]))$/gi.test(o.emptime.value)){

alert('雇佣日期:必须是日期格式,即2013-03-02')

return false

}

if(isNaN(o.empmoney.value)){

alert('基本工资:必须是数字(小数)')

return false

}

if(isNaN(o.emprw.value)){

alert('奖金:必须是数字(小数)')

return false

}

}

<form action="" method="post">

改为

<form action="" method="post" onsubmit="javascript:return chkfrm(this)">

即可

我来举个例子,很简单的

<!DOCTYPE html>

<html>

<head>

<meta charset="UTF-8">

<title>Insert title here</title>

<script type="text/javascript">

function formCheck(){//表单验证

var userForm=document.forms.userForm

if(userForm.username.value==null||userForm.username.value.length<=0){

alert("用户名不能为空")

return false

}else if(userForm.username.value.length<6||userForm.username.value.length>20){

alert("用户名必须为6-20位")

return false

}else if(userForm.password.value==null||userForm.password.value.length<=0){

alert("密码不能为空")

return false

}else if(userForm.password.value.length<6||userForm.password.value.length>20){

alert("密码必须为6-20位")

return false

}else{

userForm.submit()

}

}

</script>

</head>

<body>

<form action="" name="userForm">

userName:<input type="text" name="username"><br>

password:<input type="password" name="password"><br>

<input type="button" value="提交" onclick=" formCheck()">

</form>

</body>

</html>