Chrilla
Chrilla

Reputation: 21

How do I validate my form before redirecting to another page?

I'm creating a register form that I want to be validated before it sends the user to the login.html page.

Is there any way to do that with this code? I want all those fields to be more than 2 characters, right now it's enough to write 2 characters in the #firstName field and then it redirects.

$('#regForm').on('submit', function() {
        if($('#firstName, #lastName, #address, #city, #zip, #phoneNumber, #email, #inputPassword, #confirmPassword').val().length >= 2)
    {
        window.location.replace("login.html");
    } else {
        alert('You must fill in all the required fields.')
    }
    })

Upvotes: 2

Views: 101

Answers (1)

Gawel1908
Gawel1908

Reputation: 138

You can use event.preventDefault() in callback function:

$('#regForm').on('submit', function(event) {

   event.preventDefault();

   if($('#firstName, #lastName, #address, #city, #zip, #phoneNumber, #email, #inputPassword, #confirmPassword').val().length >= 2)
   {
      window.location.replace("login.html");
   } 
   else {
      alert('You must fill in all the required fields.');
   }
});

Upvotes: 1

Related Questions