JS实现表单验证功能(验证手机号是否存在,验证

JavaScript015

JS实现表单验证功能(验证手机号是否存在,验证,第1张

用正则表达式,if判断内容是否为空,为空则提示输入手机号,不为空再用正则验证内容是否符合格式

附上源码

<!DOCTYPE html>

<html>

<head>

<meta charset="utf-8">

<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">

<title>Examples</title>

<meta name="description" content="">

<meta name="keywords" content="">

<link href="" rel="stylesheet">

<style type="text/css">

*{margin: 0padding: 0}

#box{

width: 240px

height: 100px

border:1px solid gray

border-radius: 10px

padding: 30px 10px 10px 10px

margin: 100px auto 0

}

#tel{

width: 160px

height: 20px

margin: 0

padding-left:5px

}

#btn{

width: 50px

height: 25px

}

p{

margin-top: 10px

font-size: 14px

font-family: 'Microsoft YaHei'

}

</style>

</head>

<body>

<div id="box">

<input type="" name="" id="tel">

<input type="button" name="" value="确认" id="btn">

<p></p>

</div>

<script type="text/javascript">

var oBox=document.getElementById('box')

var oBtn=document.getElementById('btn')

var oP=document.getElementsByTagName('p')[0]

oBtn.onclick=function(){

var val=document.getElementById('tel').value

var reg=/^1[345678]\d{9}$/

if (val=='') {

oP.style.color="red"

oP.innerHTML="请输入手机号!"

}else if(reg.test(val)){

oP.style.color="green"

oP.innerHTML="输入正确!"

}else{

oP.style.color="red"

oP.innerHTML="输入错误,请重新输入!"

}

}

</script>

</body>

</html>

我来举个例子,很简单的

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