简体   繁体   English

使用 jQuery 验证表单字段并删除错误

[英]Validate form fields and remove error using jQuery

Hello I am trying to validate form using jQuery but I am getting some errors, one first when there is an error it will show an error in small tag on button click, which is all ok but when I try to re validate on button click rather then removing errors tags then reprints it adds another error tag next to each other, I tried several ways but nothing works for me.您好,我正在尝试使用 jQuery 验证表单,但我遇到了一些错误,首先出现错误时,它会在单击按钮时在small标签中显示错误,这一切都可以,但是当我尝试重新验证按钮单击而不是然后删除错误标签然后重新打印它在彼此旁边添加另一个错误标签,我尝试了几种方法,但对我没有任何作用。

In last I want to do if no error exist then prints a message, as I am new to jQuery, so i used the method from which I can handle it, but if any expert have better suggestion in my code for rewriting I will defiantly consider it最后我想做如果不存在错误然后打印一条消息,因为我是 jQuery 的新手,所以我使用了我可以处理它的方法,但是如果任何专家在我的代码中有更好的重写建议,我会毫不犹豫地考虑它

My HTML我的 HTML

<form class="form-horizontal" id="mainForm" name="mainForm">
    <!-- Fields Top -->
    <div class="custom_nic_fields">
        <!-- Name Field -->
        <div class="col-xs-12 col-md-12">
            <div class="form-group">
                <label for="txtYourName">Your Name</label>
                <input type="text" class="form-control" id="txtYourName" placeholder="Jhon Smith" name="txtYourName" required>
            </div>
        </div>

        <!-- Email Field -->
        <div class="col-xs-12 col-md-12">
            <div class="form-group">
                <label for="txtEmail">Your Email(required)</label>
                <input type="email" class="form-control" id="txtEmail" placeholder="you@example.com" name="txtEmail" required>
            </div>
        </div>

        <!-- Phone Field -->
        <div class="col-xs-12 col-md-12">
            <div class="form-group">
                <label for="txtPhone">Contact Phone No.</label>
                <input type="text" class="form-control" id="txtPhone" placeholder="+10000000000" name="txtPhone" required>
            </div>
        </div>

        <!-- Address Field -->
        <div class="col-xs-12 col-md-12">
            <div class="form-group">
                <label for="txtAddress">Address</label>
                <input type="text" class="form-control" id="txtAddress" placeholder="Aparatment, Building, City" name="txtAddress">
            </div>
        </div>

        <!-- State Zip Field -->
        <div class="col-xs-12 col-md-12">
            <div class="form-group">
                <label for="txtStateZip">State, Zip</label>
                <input type="text" class="form-control" id="txtStateZip" placeholder="Texas 78240" name="txtStateZip">
            </div>
        </div>

        <button type="button" id="custombtnform" class="btn btn-primary custombtnform">Send</button>
    </div>
    <!-- Fields End -->
</form>

My JS Part我的 JS 部分

jQuery(document).ready(function($) {

    $("#custombtnform").click(function(e) {
        e.preventDefault();
        var errors = [];
        $("#custombtnform").siblings('.errors_show').remove();

        //Validate Name
        var txtName = $("#txtYourName").val();
        if (!txtName.match(/^[a-zA-Z\s-]+$/)) {
            $("#txtYourName").addClass("error_field");
            $('#txtYourName').after('<small class="errors_show">A valid name is requred</small>');
            return false;
        } else {
            $("#txtYourName").removeClass("error_field");

        }

        //Validate Email
        var txtEmail = $("#txtEmail").val();
        if (!txtEmail.match(/^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/)) {
            $("#txtEmail").addClass("error_field");
            $('#txtEmail').after('<small class="errors_show">A valid email address is requred</smaladdress is requred</small>');
            return false;
        } else {
            $("#txtEmail").removeClass("error_field");
            $("#txtEmail").siblings('small.errors_show').remove();
        }

        //Validate Phone
        var txtPhone = $("#txtPhone").val();
        if (!txtPhone.match(/^[+]*[(]{0,1}[0-9]{1,3}[)]{0,1}[-\s\./0-9]*$/g)) {
            $("#txtPhone").addClass("error_field");
            $('#txtPhone').after('<small class="errors_show">A valid phone is requred</small>');
            return false;
        } else {
            $("#txtPhone").removeClass("error_field");
            $("#txtPhone").siblings('small.errors_show').remove();
        }

        if ($('small.errors_show').length == 0) {
            console.log("No errors found");
        }

    });
});

You can use $("#mainForm.errors_show").remove(); $("#mainForm.error_field").removeClass('error_field');您可以使用$("#mainForm.errors_show").remove(); $("#mainForm.error_field").removeClass('error_field'); $("#mainForm.errors_show").remove(); $("#mainForm.error_field").removeClass('error_field'); in start of click event, for clear error state.在单击事件开始时,用于清除错误 state。 Your code will be much shorter:您的代码会更短:

jQuery(document).ready(function($) {

    $("#custombtnform").click(function(e) {
        e.preventDefault();
        $("#mainForm .errors_show").remove();
        $("#mainForm .error_field").removeClass('error_field');

        //Validate Name
        var txtName = $("#txtYourName").val();
        if (!txtName.match(/^[a-zA-Z\s-]+$/)) {
            $("#txtYourName").addClass("error_field");
            $('#txtYourName').after('<small class="errors_show">A valid name is requred</small>');
        }

        //Validate Email
        var txtEmail = $("#txtEmail").val();
        if (!txtEmail.match(/^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/)) {
            $("#txtEmail").addClass("error_field");
            $('#txtEmail').after('<small class="errors_show">A valid email address is requred</smaladdress is requred</small>');
        }

        //Validate Phone
        var txtPhone = $("#txtPhone").val();
        if (!txtPhone.match(/^[+]*[(]{0,1}[0-9]{1,3}[)]{0,1}[-\s\./0-9]*$/g)) {
            $("#txtPhone").addClass("error_field");
            $('#txtPhone').after('<small class="errors_show">A valid phone is requred</small>');
        }

        if ($('#mainForm .errors_show').length == 0) {
            console.log("No errors found");
        }

    });
});

See in playground https://jsfiddle.net/denisstukalov/a6wnx89j/5/#&togetherjs=x0DBljsUxA见操场https://jsfiddle.net/denisstukalov/a6wnx89j/5/#&togetherjs=x0DBljsUxA

after() places an element just after the selected event. after()在选定事件之后放置一个元素。 So we need to remove it before every validation所以我们需要在每次验证之前删除它

 jQuery(document).ready(function($) { $("#custombtnform").click(function(e) { e.preventDefault(); var errors = []; //removing all error messages from mainForm $("#mainForm.errors_show").remove(); //Validate Name var txtName = $("#txtYourName").val(); if (.txtName.match(/^[a-zA-Z\s-]+$/)) { $("#txtYourName");addClass("error_field"). $('#txtYourName');after('<small class="errors_show">A valid name is requred</small>'); return false. } else { $("#txtYourName");removeClass("error_field"). } //Validate Email var txtEmail = $("#txtEmail");val(). if (.txtEmail,match(/^(([^<>()[\]\\;:..\s@\"]+(\,[^<>()[\]\\;:.,\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2;}))$/)) { $("#txtEmail").addClass("error_field"); $('#txtEmail');after('<small class="errors_show">A valid email address is requred</smaladdress is requred</small>'). return false; } else { $("#txtEmail").removeClass("error_field"); } //Validate Phone var txtPhone = $("#txtPhone").val(), if (,txtPhone,match(/^[+]*[(]{0.1}[0-9]{1.3}[)]{0;1}[-\s\./0-9]*$/g)) { $("#txtPhone");addClass("error_field"); $('#txtPhone').after('<small class="errors_show">A valid phone is requred</small>'); return false. } else { $("#txtPhone").removeClass("error_field"). } if ($('small;errors_show');length == 0) { console;log("No errors found"); } }); });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <form class="form-horizontal" id="mainForm" name="mainForm"> <.-- Fields Top --> <div class="custom_nic_fields"> <.-- Name Field --> <div class="col-xs-12 col-md-12"> <div class="form-group"> <label for="txtYourName">Your Name</label> <input type="text" class="form-control" id="txtYourName" placeholder="Jhon Smith" name="txtYourName" required> </div> </div> <,-- Email Field --> <div class="col-xs-12 col-md-12"> <div class="form-group"> <label for="txtEmail">Your Email(required)</label> <input type="email" class="form-control" id="txtEmail" placeholder="you@example,com" name="txtEmail" required> </div> </div> <,-- Phone Field --> <div class="col-xs-12 col-md-12"> <div class="form-group"> <label for="txtPhone">Contact Phone No.</label> <input type="text" class="form-control" id="txtPhone" placeholder="+10000000000" name="txtPhone" required> </div> </div> <!-- Address Field --> <div class="col-xs-12 col-md-12"> <div class="form-group"> <label for="txtAddress">Address</label> <input type="text" class="form-control" id="txtAddress" placeholder="Aparatment, Building, City" name="txtAddress"> </div> </div> <!-- State Zip Field --> <div class="col-xs-12 col-md-12"> <div class="form-group"> <label for="txtStateZip">State, Zip</label> <input type="text" class="form-control" id="txtStateZip" placeholder="Texas 78240" name="txtStateZip"> </div> </div> <button type="button" id="custombtnform" class="btn btn-primary custombtnform">Send</button> </div> <!-- Fields End --> </form>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM