Check variables in jQuery?

Asked

Viewed 2,234 times

3

There is a smarter way to write this verification code, the IF?

    jQuery("#oformulario").submit(function(){

        var nome            = jQuery("#nome").val();
        var email           = jQuery("#email").val();
        var telefone        = jQuery("#telefone").val();
        var tipodecontato   = jQuery("#tipodecontato").val();
        var mensagem        = jQuery("#mensagem").val();
        var send            = jQuery("#send").attr("name");

        if(nome != "" && email != "" && telefone != "" && tipodecontato != "" && mensagem != "" && send == "enviar"){

2 answers

3

If you want to do a "simple" validation, ie just check if the input is empty or can’t do so:

if(!$('form').serialize().match(/=&|=$/)) { // correr código

Example: http://jsfiddle.net/xr5z2rnp/1/

What . serialize() does is transform the input into a string that can be passed to ajax for example.

In this string, go key pairs|value (chave=valor), where each pair is separated by &. Now that means if there’s one like it (=) followed by & then there is an empty value! I used the negation operator (!) there being a =& in the string the match gives true, with the ! invert to false. I joined too =$ looking for the equal sign as the last character of the string.

If you’re using ajax, you can do it like this:

var meudata = $('form').serialize();
if(!meudata.match(/=&|=$/)) { // fazer ajax

and in the field data date of ajax, do data: meudata,.

If you want to do a more detailed validation, mine another answer can help.

  • has a small bug, the last field is only = then even not filling it the validation says this true... another difficulty would be with possible non mandatory fields.

  • @Jader well looked after, thank you. I joined too =$ for strings that end up worthless.

2

You could do something like this:

$("#oformulario").submit(function(){
    var erro = false;
    $(this).find('input:not(.campo-nao-obrigatorio)').each(function() {
        if ($(this).val() == '') erro = true;
    });

        if(erro == false && $("#send").attr("name") == "enviar") {

would not need to declare all form fields...

Browser other questions tagged

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