HTML JS 数据校验

时间:2023-03-09 20:15:18
HTML JS 数据校验

用到了html字符串校验,这里记录一下。

 <html>
<head>
<script type="text/javascript">
function on_click(){
var email = document.getElementById("input1").value.trim();
var telph = document.getElementById("input2").value.trim(); if(email == "" ||telph == ""){
alert("The email or telph is blank!!!");
return false;
} if (email.indexOf("@") == -1){
alert("an @ is not in an email !!!");
return false;
} var re = /^([0-9]{3}-)?[0-9]{3}-[0-9]{4}$/;
if (re.test(telph) == false){
alert("telph number is not match xxx-xxxx or xxx-xxx-xxxx")
return false;
} alert("ok, email:" + email + ", telephone:" + telph);
return true;
}
</script>
</head> <body>
email: <input id = "input1"> </input> <br> <!--必须有@-->
telph: <input id = "input2"> </input> <br> <!--必须满足xxx-xxxx or xxx-xxx-xxxx-->
<button type="button" onclick=on_click()>test</button>
</body>
</html>

如图:

校验两个字段均不能为空

校验email字段必须包含@

校验telph字段必须满足正则表达式

HTML JS 数据校验