JavaScript基础(javascript表单验证)

这一篇的内容主要以代码的形式直接展示,第一部分代码是验证用户是否输入

<!DOCTYPE html>
<html>
    <head>
        <script type="text/javascript">
        //JavaScript的脚本是编译执行,脚本会一句一句的往下执行,如果因此以下两个函数的顺序不能颠倒,一开始学习的时候我一直把两个函数颠倒了导致一直不能正确展示
        function check(field,alerttxt){
            with(field){//有了 With 语句,在存取对象属性和方法时就不用重复指定参考对象,在 With 语句块中,凡是 JavaScript 不识别的属性和方法都和该语句块指定的对象有关
            //这样说可能还不明白,看这一题,以下在引用value的时候有了with所以只需要直接用value,如果不再with范围内需要使用field.value了。
                if(value == null ||value == ""){
                    alert(alerttxt);
                    return false
                }
                else{
                    return true
                }
            }
        }
        function MyFunction(thisform){
            with(thisform){
                if(check(email,"Check your Email!")==false){
                    email.focus();//如果用户没有输入邮箱,就弹窗然后把光标放到输入框内
                    return false
                }
                
            }
        }
        </script>
    </head>
    <body>
        <form action="hello.html" onsubmit="return MyFunction(this)" method="post">//注意这里的return不能丢掉
            Email:<input type="text" name = "email"/>
            <input type = "submit" value = "Submit">
        </form>


    </body>
</html>

接下来第二部分是验证用户输入的邮箱是否符合规范

<!DOCTYPE html>
<html>
    <head>
        <script type="text/javascript">
        function check(field,alerttxt){
            with(field){
                start = value.indexOf("@");
                end = value.lastIndexOf(".");
                if(start < 1|| end-start < 2){
                    alert(alerttxt);
                    return false
                }
                else{
                    return true
                }
            }
        }
        function MyFunction(thisform){
            with(thisform){
                if(check(email,"Check your Email!")==false){
                    email.focus();
                    return false
                }
                
            }
        }
        </script>
    </head>
    <body>
        <form action="hello.html" onsubmit="return MyFunction(this);" method="post">
            Email:<input type="text" name = "email"/>
            <input type = "submit" value = "Submit">
        </form>
    </body>


你可能感兴趣的:(JavaScript基础(javascript表单验证))