Kian
Kian

Reputation: 19

How can I stop the form submit when I input wrong type info in the form using javascript?

function validation() {
var isNameValid = checkName();
var isEmailValid = checkEmail();
var isCorrectPassword = checkPassword();
var isSame = checkSame();

// Check if they are all true -> return true
    // Else return false
if (isNameValid && isEmailValid && isSame && isCorrectPassword) {

    return true;

   } 
   else {
    return false;
  }
}

This is function for validation, just didn't put all the sub functions here, they're all doing the same thing: check if input is empty and show error message in span tag and return false if there's a error. I call this validation function from "onclick" of the form's submit button But the form still can be submitted even the passwords are different and returned false, how can I fix this Thank you for any advice.

Upvotes: 0

Views: 767

Answers (2)

Diego ZoracKy
Diego ZoracKy

Reputation: 2285

You should call the function on onsubmit instead of onclick

Upvotes: 0

What have you tried
What have you tried

Reputation: 11148

I'm assuming this validation function is being called in the form's submit event - this is important. Simply prevent the default action:

$('#form').on('submit', function(event){
  return isValidForm();
});

function isValidForm(){
  var isNameValid = checkName();
  var isEmailValid = checkEmail();
  var isCorrectPassword = checkPassword();
  var isSame = checkSame();

  // Check if they are all true -> return true
  // Else return false
  if (isNameValid && isEmailValid && isSame && isCorrectPassword) {
    return true;
  } else {
    return false;
  }
}

Upvotes: 1

Related Questions