Validate all inputs in SUBMIT

Asked

Viewed 175 times

0

I have a function that validates my fields in the event focusout, however, now I need to go through all the fields in the submit of form, I know I should wear one for, but I don’t know how.

$("input[type='text'],textarea").focusout(function () {
    validar($(this))
});

$("#formcontato").submit(function (event) {
    event.preventDefault();
    //O for entraria aqui?
});

$('input, textarea').keypress(function (e) {
    if (e.which == 13 && validar()) {
        request();
        return false;
    }
});

function request() {
    $.ajax({
        url: "minha api...",
        method: "POST",
        data: $(this).serialize(),
        dataType: "json",
        beforeSend: function () {
            //antesEnvio();
        },
        success: function () {
            //sucessoRequest();
        },
        error: function () {
            //erroRequest();
        }
    });
}


function validar(input) {
    var valido = false;
    if (input.attr("id") === "email") {
        var filtro = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/;
        if (filtro.test(input.val())) {
            input.css("border-color", "green");
        } else {
            input.css("border-color", "red");
            valido = false;
        }
    }
    else if (input.val() === "") {
        input.css("border-color", "red");
        valido = false;
    }
    else if (input.val() != "") {
        input.css("border-color", "green");
    }

    return valido;
}
  • 1

    An easy way is to define global variables with the false value for each validation, if they pass they will receive true, at Submit time just check if all are true.

2 answers

4


Following the same validation pattern you are using now, I say to do the following:

First you must do your job validate() return true whenever the field is OK, and continue returning false when something is wrong in the field.

Then just put the code below in the Submit of your form.

Would look like this:

$("#formcontato").submit(function (event) {
    event.preventDefault();
    var success =[],
        inputs = this.elements;

    for (var i = 0, length = inputs.length; i < length; i++ {
        success.push(validar($(inputs[i])));
    }

    if (success.indexOf(false) >= 0) {
        return;
    }

    this.submit();
});

Explaining what I did:

The variable Success is an array. Every loop of the for function validate() will return true or false (if the field is ok or not), and this return is always inserted into the Success array variable via the push method().

The method push() serves to insert a new value at the end of an array.

That is, at the end of the loop our array will be filled with several true and false.

Following...

The indexof() method serves to search an array for a certain value. If it finds the value passed as argument it returns the position within the array (index) where the value is. If it DOES NOT find it it simply returns the value -1.

In our case I check if there is a FALSE in the Success array. If so, I interrupt the script before calling Submit() manually.

  • Thank you very much, you saved me. But could you explain the function? My doubts are what these snippets: Success.push(validate($(inputs[i])); ------ Success.indexof(false) >= 0

  • @Tiagosilveira, I edited my answer to answer your questions. :)

3

To validate text and email in Submit you can combine the type plus required HTML5 that it will not allow submission if the data is invalid.

Example

<form>
    <input type="email" required>E-mail
    <br>
    <input type="text" required>Texto
    <br>
    <input type="submit">Enviar
</form>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.