JavaScript表单验证

142 阅读1分钟

offsetHeight和clientHeight的区别

      console.log( 'offsetHeight ' ,document.documentElement.offsetHeight)
    /* offsetHeight  获取的是document的实际高度*/
    /* ☆ 包括页面有滚动条的情况下,获取页面整个的高度,并不是一屏的高度*/

    console.log( 'clientHeight ' ,document.documentElement.clientHeight)
    /* clientHeight 获取的是可视区域的高度 */

JavaScript 表单验证

    <body>
        <form action="success.html" id="form">
            <p>
                用户名:<input type="text" name="username" id="username">
            </p>
            <input type="submit" value="提交">
        </form>
        <script>
            /* 字符串非空验证 */
            let form = document.getElementById('form')
            form.onsubmit = function () {
                let username = document.getElementById('username').value
                /* .trim()去除字符串左右空格 */
                if (username.trim() == '') {
                    alert('用户名不能为空')
                    /* 阻止表单提交的默认事件 */
                    return false
                }
                /* 继续执行默认事件 */
                /* return true */


                /* 字符串查找验证 */
                var str="this is Javascript"
                str.indexOf( 'is',3 )
                /* 从下标是3的位置开始寻找,找的到返回对应的下标找不到返回-1*/
            }
            
           </script>
    </body>
    
    

JavaScript表单验证特效案例

  <body>
    <form action="success.html">
        <p>
             email:<input type="text" name="" id="eml" onblur="brfn()"><span></span>
        </p>
        <input type="submit" value="提交">
    </form>
    <script>
        let form=document.querySelector('form')
        let eml=document.getElementById('eml')
        let sp=document.querySelector('span')
        function brfn(){

            if(eml.value.trim() ==''){
                eml.style.borderColor='red'
                sp.innerHTML='不能为空'
                sp.style.color='red'
                return false
            }
            eml.style.borderColor=''
            sp.style.color=''
            sp.innerHTML=''
            return ture
        }
        form.onsubmit=function(){
            if(brfn()){
                return true
            }
            return false
        }
     </script>
</body>