Problem with field validation with ajax

1

I personally did a validation via ajax on my form site that when the user does not fill in the field and tries to submit the form it takes the inputs and adds a red border until it's right but when the fields are filled and it sends the form the edges do not disappear wanted them to disappear when the user fill in the fields or when to send the form he simply leaves the boras without this red marking follows a print of the screen of one of my form and the code that I did:

That's how it goes when I send without filling

AfterfillingandsendingitcontinueswiththebordersandthemessagethatIaddedbehindthemodalyouwillbeabletoseethatwhensendingitcontinueslikethis:

JS:

//ContactUs$(".send-form").click(function (e) {
    e.preventDefault();

    var data = $('form').serializeArray();

    var cont = 0;
    $("#form .input-contact").each(function(){
        if($(this).val() == "")
        {
            $(".required-fields-contact").show();
            $(this).css({"border" : "1px solid #F00", "padding": "2px"});
            cont++;
        }
    });
    if(cont != 0)
    {
        return false;
    }

    //Ajax post data to server
    $('.loaderImage').show();
    $.ajax({
        type: 'POST',
        url: '/contato',
        data: data,
        dataType: 'json',
        success: function (data) {
            $('#modal-success').modal('show');
            $('.loaderImage').hide();
            $('form').trigger("reset");
        },
        error: function (data) {
            //console.log(data);
        }
    });
});

NOTE: Sitelink is at the beginning of the question if you want to test

    
asked by anonymous 05.09.2017 / 17:21

1 answer

1

Why not use a ready-made script? So much simpler. It will do all the checking of when the field is or not according to the rules. I indicate the link

Anyway, if you want to keep the current solution, your code should delete the tag you added, something like this:

success: function (data) {
    $('#modal-success').modal('show');
    $('.loaderImage').hide();
    $('form').trigger("reset");

    $(".required-fields-contact").hide();        
    $("#form .input-contact").each(function(){
        $(this).removeAttr("style");
    });
},

However, I would recommend you create a class to flag the error and then remove it:

$("#form .input-contact").each(function(){
    if($(this).val() == "")
    {
        $(".required-fields-contact").show();
        $(this).addClass("error");
        cont++;
    }
});

e:

success: function (data) {
    $('#modal-success').modal('show');
    $('.loaderImage').hide();
    $('form').trigger("reset");

    $(".required-fields-contact").hide();    
    $("#form .input-contact").each(function(){
        $(this).removeClass("error");
    });
},
    
05.09.2017 / 17:37