Check jQuery variables?

3

Is there a smarter way to write this verification code, 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"){
    
asked by anonymous 09.08.2014 / 20:41

2 answers

3

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

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

Example: link

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

In this string, value pairs ( chave=valor ), where each pair is separated by & . This means that if there is an equal ( = ) followed by & then there is an empty value! I used the negation operator ( ! ) because having a =& in the string matches true, with ! inverted to false. I also added =$ which looks for the equal sign as the last character of the string.

If you are using ajax, you can do this:

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

and in the data ajax date field, it does data: meudata, .

If you want to do a more detailed validation, my other answer might help.

    
10.08.2014 / 00:46
2

I'd like to 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") {

I would not need to declare all form fields ...

    
09.08.2014 / 22:52