0

I am trying below code for email/password validation but form is not submitting after successful validation. Any help ?.

$("form").submit(function(e) {
  e.preventDefault();
  const email = $(".email").val();
  const password = $(".password").val();
  const re = /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
  console.log(re.test(String(email).toLowerCase()));
  $('.email_v').text('');
  $('.pass_v').text('');
  if (!re.test(String(email).toLowerCase())) {
    $('.email_v').text("Please provide Valid Email Address");
    return false;
  }
  if (password.length < 6) {
    $('.pass_v').text("Password must be atleast 6 characters");
    return false;
  }
  return true;
});
3
  • 1
    e.preventDefault() prevents the form from submitting. Commented Dec 21, 2020 at 6:02
  • 1
    Why do you use toLowerCase() when the regexp matches both upper and lower case? And it's not necessary to call String(), since .val() always returns a string. Commented Dec 21, 2020 at 6:04
  • 1
    Move the line e.preventDefault() to the places returning false or don't do any returns and use e.preventDefault if validation fails at the end of your callback Commented Dec 21, 2020 at 6:05

1 Answer 1

2

e.preventDefault() called at the beginning of the script stops the form from being sent.

See the docs:

The preventDefault() method cancels the event if it is cancelable, meaning that the default action that belongs to the event will not occur. For example, this can be useful when: Clicking on a "Submit" button, prevent it from submitting a form. Clicking on a link, prevent the link from following the URL.

https://www.w3schools.com/jsref/event_preventdefault.asp

You may move preventDefault to the places where validation fails, as suggested.

Sign up to request clarification or add additional context in comments.

1 Comment

There are much better documentations than W3Schools, please use those instead.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.