JQuery表单输入字段验证,不使用插件

时间:2018-06-04 07:14:39

标签: javascript jquery html5 validation

我正在使用表单验证我花了2,3天时间来解决这个问题,但是无法实现它。我刚刚开始研究jquery。我刚刚开始研究jquery。我的问题是在这种形式中,我应该如何添加其他输入字段,如radio, checkbox, select option, upload file,此输入字段应该验证,并且在我的代码email, phone number中也未正确验证,我希望在提交后获得成功消息我写的表单和CSS显示:无通过jquery我想显示成功消息。成功提交后,表单将再次重置。在这里,如果我有超过1个文本字段,我打算根据所需的attr示例进行表单应该使用data-validate attr使用相同的代码进行验证 所以,我已经尝试过这样的了。任何人都可以帮我解决这个问题吗? 任何帮助将不胜感激。

 $('.success_msg').fadeIn().delay(3000).fadeOut();
 $('input , textarea , select').val('').removeClass('input-error');
 event.preventDefault();



var Validator = function(formObject) {
        this.form = $(formObject);

        var Elements = {
            name: {
                reg: /^[a-zA-Z]{2,20}$/,
                error: "Not a valid name.",
            },

            email: {
                reg: /^[a-z-0-9_+.-]+\@([a-z0-9-]+\.)+[a-z0-9]{2,7}$/i,
                error: "Not a valid e-mail address.",
            },
		   phone: {
                reg: /^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$/,
                error: "Not a valid number.",
            },

            message: {
                reg: /^(?!\s*$).+/,
                error: "Message field cannot be empty.",
            },
        };

        var handleError = function(element, message) {
            element.addClass('input-error');
            var $err_msg = element.parent('div');
            $err_msg.find('.error').remove();
            var error = $('<div class="error"></div>').text(message);
            error.appendTo($err_msg);
            element.keyup(function() {
                $(error).fadeOut(1000, function() {
                    element.removeClass('input-error');
                });
            });

        };

        this.validate = function() {
        		var errorCount = 0;
            this.form.find("input, textarea").each(function(index, field){
                var type = $(field).data("validation");
                var validation = Elements[type];
                if (validation){
                    if (!validation.reg.test($(field).val())){
                    		errorCount++;
                        handleError($(field), validation.error);
                    }            
                }
            })
        		return errorCount == 0;
        };
    };

    $(function(){
        $("form#test").on("submit", function(event){
            //event.preventDefault();
            return new Validator(this).validate(); // "this" here refers to the form
            
        })
    })
&#13;
    body {
        background: #fff;
        color: #333;
        font: 76% Verdana, sans-serif;
    }

    form {
        margin: 1em 0 0 2em;
        width: 90%;
    }

    fieldset {
        margin: 0;
        border: 1px solid #ccc;
        padding-bottom: 1em;
    }

    legend {
        font-weight: bold;
        text-transform: uppercase;
    }


    label {
        float: left;
        width: 5em;
        padding-right: 2em;
        font-weight: bold;
    }
    div {
    	margin-bottom: 30px;
    }
    input {
        font: 1em Verdana, sans-serif;
    }

    fieldset ul li input {
        float: left;
        width: 120px;
        border: 1px solid #ccc;
    }

    textarea {
        width: 300px;
        height: 200px;
        border: 1px solid #ccc;
        font: 1em Verdana, sans-serif;
    }

    form p {
        margin: 0;
        padding: 0.4em 0 0 7em;
    }

    form p input {
        background: #666;
        color: #fff;
        font-weight: bold;
    }


    div.error {
        clear: left;
        margin-left: 5.3em;
        color: red;
        padding-right: 1.3em;
        height: 100%;
        padding-bottom: 0.3em;
        line-height: 1.3;
    }

    .input-error {
        background: #ff9;
        border: 1px solid red;
    }
.success_msg {
    width: 350px;
    line-height: 40px;
    border: 1px solid green;
    border-radius: 5px;
    background-color: rgba(213, 255, 187, 0.7);
    display: none;
    position: absolute;
    bottom: 5px;
    left: 50%;
    transform: translateX(-50%);
    z-index: 999;
    text-align: center;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="#" method="post" id="test">

    <fieldset>

    <legend>Contact information</legend>


    <div>
        <label for="firstname">Firstname:</label>
        <input type="text" name="firstname" id="firstname" data-validation="name" />
    </div>
    	

    <div>
        <label for="lastname">Lastname:</label>
        <input type="text" name="lastname" id="lastname" data-validation="name" />
    </div>

    <div>
        <label for="email">Email:</label>
        <input type="email" name="email" id="email" data-validation="email"/>
        
    </div>
	<div>
      <label for="phone">phone</label>
      <input type="number" name="phone" id="phone" data-validation="phone" />
    </div>
	    
	<div>
      <label>Gender:</label>
      <input type="radio" name="gender" value="male" data-validation="gender" />
      <input type="radio" name="gender" value="female" data-validation="gender">
    </div>

    <div>
      <label>select</label>
      <input type="checkbox" name="checkbox" id="checkbox1" value="demo1" data-validation="checkbox" />
      <input type="checkbox" name="checkbox" id="checkbox2" value="demo2" data-validation="checkbox" />
      <input type="checkbox" name="checkbox" id="checkbox3" value="demo3" ata-validation="checkbox" />
    </div>

    <select data-validation="selectOption">
      <option value="">Select any option</option>
      <option value="red">Red</option>
      <option value="blue">Blue</option>
      <option value="green">Green</option>
    </select>
	    
	<div>
      <label>Upload:</label>
      <input type="file" name="file" id="file" data-validation="file" />
    </div>
   
    <div>  
        <label for="message">Message:</label>
        <textarea id="message" name="message" cols="30" rows="15" data-validation="message"></textarea>
    </div>

    <p><input type="submit" name="send" id="send" value="Send" /></p>

    </fieldset>
	 <div class="success_msg">
      	<p>Form submitted Successfully</p>
      </div> 
	</form>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:0)

将此代码用于两个示例字段电子邮件和密码:

<!DOCTYPE html>
<html lang="en">

<head>
    <script src="jquery-3.4.0.min.js"></script>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <style>
        #txt1{

        margin-left:23px;
        border-radius: 12px;
       }
       #txt2{
        border-radius: 12px;
       }
       #btn1{
        border-radius: 12px;
        width: 8em;  height: 2em;
        cursor:pointer;
        background-color: #008CBA;
       }
       #lbl1,#lbl2{
        font-family: "Comic Sans MS", cursive, sans-serif;
        color:red;
       }
    </style>
</head>

<body>
    <div class="container">
        <form>
            <center> <label id="lbl1">Email: </label><input type="text" id="txt1"></center></input><br>
            <center><label id="lbl2">Password: </label><input type="password" id="txt2"></center></input>
            <br><br>
            <center><input type="button" id="btn1" name="btn1" value="Login" style="color:darkblue;font-size:15px;"></center></input>
        </form>

    </div>
    <script>
        $(document).ready(function () {
            $('#btn1').click(function () {
                var email = $('#txt1').val();
                var pass = $('#txt2').val();
                if (email == '') {
                    $('input[type="text"]').css("border", "2px solid red");
                    $("#txt1").parent().after("<div class='validation' style='color:red;margin-left:93px;'><center>Please enter email address</center></div>");
                    alert("hi");
                }
                else {

                }
                if (pass == '') {
                    $('input[type="password"]').css("border", "2px solid red");
                    $("#txt2").parent().after("<div class='validationp' style='color:red;margin-left:70px;'><center>Please enter password</center></div>");
                }
                $('input[type="text"]').keydown(function () {
                    $('input[type="text"]').css("border", "");
                    $(".validation").remove();
                });
                $('input[type="password"]').keydown(function () {
                    $('input[type="password"]').css("border", "");
                    $(".validationp").remove();

                });

            });
        });

    </script>
</body>

</html>