js表单验证代码怎么写

JavaScript020

js表单验证代码怎么写,第1张

我来举个例子,很简单的

<!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>

可以在submit按钮上添加onclick事件。通过创建function函数进行验证,全部通过后执行form.submit(),错误则利用alert或者innerHTML显示错误信息。