• jq实战-表单验证


    作为学习的记录,方便大家查看,废话不多说,直接上代码

    html 结构:

    <form action="a.php" method="" class="form">
        <div>
            <label for="username">用户名:</label>
            <input id="username" class="required" type="text" />
        </div>
        <div>
            <label for="email">邮箱:</label>
            <input id="email" class="required" type="text" />
        </div>
        <div><input id="send" type="submit" /></div>
    </form> 

    jq代码:

    $("form :input.required").each(function(){
            var $required = $('<strong class="high">*</strong>');
            $(this).parent().append($required);
        });
        $("form :input").blur(function(){
            var $parent = $(this).parent();
            $parent.find(".formtips").remove(); //删除多余重复
            // 验证用户名
            if($(this).is('#username')){
                if(this.value == ""|| this.value.length<6 ){
                    var errorMsg = "请输入6位用户名" ;
                    $parent.append($('<span class="formtips onError">'+errorMsg+'</span>'));
                }else{
                    var okMsg = "输入正确";
                    $parent.append($('<span class="formtips okMsg">'+okMsg+'</span>'));
                }
            }
            // 验证邮箱
            if($(this).is('#email')){
                if(this.value == "" ){ //|| (this.value!="" && !/.+@.+.[a-zA-Z] {2,4}$/.test(this.value)
                    var errorMsg = "请输入正确的E-mail" ;
                    $parent.append($('<span class="formtips onError">'+errorMsg+'</span>'));
                }else{
                    var okMsg = "输入正确";
                    $parent.append($('<span class="formtips okMsg">'+okMsg+'</span>'));
                }
            }
        }).keyup(function() {
            $(this).triggerHandler('blur');
        }).focus(function(){
            $(this).triggerHandler('blur');
        });
    
        $("#send").click(function(){
            $("form .required:input").trigger('blur');
            var numError = $("form .onError").length;
            var $id = $("form .onError").prevAll(".required").attr("id");
            if(numError){
                if(numError > 1){
                    $("#username").focus();
                }else if($id == "email"){
                    $("#email").focus();
            }
                return false;
            }
            alert("注册成功,密码已发送到你的邮箱,请查收");
        });

    学习代码是需要多跑几遍的!

  • 相关阅读:
    nohub
    swoole聊天室
    swoole httpserver学习
    swore tcp服务学习
    ps查看命令
    nginx和php-fpm调用方式
    Unix/Linux环境C编程入门教程(1) Solaris 11 64bit环境搭建
    Unix/Linux环境C编程入门教程(1) Solaris 11 64bit环境搭建
    C语言入门(4)——常量、变量与赋值
    C语言入门(3)——对Hello World程序的解释
  • 原文地址:https://www.cnblogs.com/pangzi666/p/5074470.html
Copyright © 2020-2023  润新知