html表单js验证输入的信息是否正确
- <script type="text/javascript">
- //表单验证。from加id,表单加对应id
- window.onload = function(){
- document.getElementById("form").onsubmit = function(){
- return checkUsername() && checkMobilePhone(); //有几个验证就加几个
- };
- document.getElementById("username").onblur = checkUsername;
- document.getElementById("telphone").onblur = checkMobilePhone;
- }
- function checkUsername(){
- var username = document.getElementById("username").value;
- var reg_username =/[\u4e00-\u9fa5]/;
- var flag = reg_username.test(username);
- var s_username = document.getElementById("s_username");
- if(flag){
- return true; //正确继续往下执行
- }else{
- window.alert("请输入正确的姓名或称呼");//页面弹窗提醒信息(上边错误的也可以添加弹窗提醒)
- return false; //错误停止执行
- }
- }
- function checkMobilePhone() {
- //定义正则表达式的变量:1.手机号正则,/^[1][3,4,5,6,7,8,9][0-9]{9}$/ //2.电话号码正则:/^(([0\+]\d{2,3}-)?(0\d{2,3})-)(\d{7,8})(-(\d{3,}))?$/
- var telphone = document.getElementById("telphone").value;
- var phoneReg= /^[1][3,4,5,6,7,8,9][0-9]{9}$/;
- var flag = phoneReg.test(telphone);
- var mobile_input = document.getElementById("mobile_input");
- if(flag)
- {
- return true;
- }else{
- window.alert("请输入正确的手机号码");
- return false;
- }
- }
- function checkform(){
- //表单总确认
- if(checkUsername() && checkMobilePhone()==true){ //只有所有验证都通过才继续执行
- return true;
- }else{
- window.alert("请您核对一下您的注册信息是否有误");
- return false;
- }
- }
- </script>
- <form action="{pboot:msgaction}" method="post" id="form">
- 联系人:<input type="text" name="contacts" id="username">
- 手机:<input type="text" name="mobile" id="telphone" >
- 内容:<input type="text" name="content" >
- <button type="submit" id="registerBtn" οnclick="checkform();">提交</button>
- </form>
以上代码验证了姓名和手机号,from添加id,需要验证的表单也要添加id
当然你也可以添加多个验证使用function checkUsername(),表单中添加对应id