js----使用正则表达式进行简单的表单验证

<h1>表单验证</h1>
    <form action="" method="post" name="myform" onsubmit="judge()">
        <tr>
                姓名:<input type="text" name="name">
        </tr>
        <tr>
                手机号码:<input type="text" name="phone">
        </tr>
        <tr>
                邮箱:<input type="text" name="email">
        </tr>
        <input type="submit" value="提交">
    </form>
    <script>
        //judge();
        function isname(name){
            var nameRegExp=/[\u4E00-\u9FA5]{2,4}/;
            return nameRegExp.test(name);
        }
        function isphone(phone){
            var phoneRegExp=/[0-9]{11}/;
            return phoneRegExp.test(phone);
        }
        function isEmail(email){
            var emailRegExp=/^[a-zA-Z0-9]+@([a-zA-Z0-9]+\.)+(com|cn|net|org)$/;
            return emailRegExp.test(email);
        }
        function judge(){
            if(!isname(document.forms["myform"]["name"].value)){
                alert("请输入正确的姓名格式");
                return false;
            }
            if(!isphone(document.forms["myform"]["phone"].value)){
                alert("请输入正确的电话格式");
                return false;
            }
            if(!isEmail(document.forms["myform"]["email"].value)){
                alert("请输入正确的邮件格式");
                return false;
            }
            alert("验证成功");
            return false;
        }
    </script>
</body>

其中

form标签有个属性是onsubmit,表示点击的发送的时候调用的函数

猜你喜欢

转载自blog.csdn.net/scwMason/article/details/81563242