Murilo Pereira
Murilo Pereira

Reputation: 109

JavaScript if statement ignores condition

I'm have a JavaScript code to validate my contact form and do the POST to PHP script, the problem is that script ignors the IF statement and do the post while the response from my validateForm function is false.

If validateForm() returns false, it's still doing the POST action

Here's a print of console with the result of the function

Result

My JS code:

    $(document).ready(function() {
    $("form[name='contactf']").submit(function(e) {             
        // do the extra stuff here      
        e.preventDefault();
        console.log(validateForm());
        if(validateForm()){                     
            $.ajax({                
                type: "POST",
                url: "mail.php",
                data: $(this).serialize(),            
                success: function(data) {                   
                    if(data.message == 'success'){                      
                        M.toast({html: 'Mensagem enviada com sucesso!'})
                        $('#first_name').val('');
                        $('#last_name').val('');
                        $('#subject').val('');
                        $('#email').val('');
                        $('#phone').val('');
                        $('#details').val('');
                    }else if(data.message == 'error'){
                        M.toast({html: 'Ops... Tente novamente dentro de alguns minutos.'})
                    }
                }
            })
        }
        else
            ;
    })
    function validateForm()
    {
        var name=document.forms["contactf"]["first_name"].value;
        var surname=document.forms["contactf"]["last_name"].value;
        var subject=document.forms["contactf"]["subject"].value;
        var mail=document.forms["contactf"]["email"].value;
        var phone=document.forms["contactf"]["phone"].value;
        var details=document.forms["contactf"]["details"].value;
        var isnum = /^\d+$/.test(phone);        
        if(!isnum){
            M.toast({html: 'O telefone deve conter apenas números!'});
            return false;
        }       
        else if (!name || !surname || !subject || !mail || !phone || !details)
        {
            M.toast({html: 'Preencha todos os campos!'})
            return false;
        }
        else
            return true;        
    }   
    function id( el ){
        return document.getElementById( el );
    }
})  

Upvotes: 0

Views: 103

Answers (2)

Delowar Hossain
Delowar Hossain

Reputation: 385

You need to change the else if condition. Write the condition like:

else if (name==null || name=="" || surname==null || surname=="" || subject==null || subject=="" || mail==null || mail=="" || phone==null || phone=="" || details==null || details=="")

Don't use Comma (,) for separation.

Upvotes: 0

Peter B
Peter B

Reputation: 24247

Your boolean logic is wrong.

Instead you can use !value which produces true if value is null or an empty string, and then OR all of them using ||.

This is based on type coercion into Boolean values, for more on this see e.g. this MDN page

Example:

function validateForm(v1, v2, v3) {
  var name = v1;
  var surname = v2;
  var subject = v3;

  if (!name || !surname || !subject)
    return false;
  else
    return true;
}

console.log(validateForm(null, null, null));
console.log(validateForm(null, "", "Test"));
console.log(validateForm("John", "Smith", "Test"));

Upvotes: 2

Related Questions