-3

I am trying to validate an email address to make sure its correct. e.g Includes "@" symbol. What do I add to my existing code?

Here is my code for the email address with other inputs in the form:

$(".next").click(function(){

//text inputs
  if(!document.getElementById('fullname').value) {
    alert('Full Name is required');
    return false;
  }

  else if(!document.getElementById('email').value) {
    alert('Email is required');
    return false;
  }

  else if(!document.getElementById('phone').value) {
    alert('Phone Number is required');
    return false;
  }

  else if(!document.getElementById('age').value) {
    alert('Age is required');
    return false;
  }
Martin54
  • 1,349
  • 2
  • 13
  • 34
Joe
  • 5
  • 3
  • you can just simply use `HTML5 form validity` https://stackoverflow.com/questions/19605773/html5-email-validation – masterpreenz Sep 03 '17 at 01:31
  • I need to code in terms of Javascript, my code will not allow your answer. How can I test for "@" symbol in Java – Joe Sep 03 '17 at 01:34
  • What do you mean by testing for "@" symbol in java ? Can you be specific please – Chetan_Vasudevan Sep 03 '17 at 01:35
  • You can check `HTML5 form validity` by `inputElement.checkValidity()` check https://stackoverflow.com/questions/5846382/a-way-to-check-validity-of-html5-forms – masterpreenz Sep 03 '17 at 01:36
  • If the input does not have an "@" then the code will return an alert. For example: hellogmail.com vs hello@gmail.com (hello@gmail.com will work, while hellogmail.com will not) – Joe Sep 03 '17 at 01:37

1 Answers1

1

On your email input you can especify the type like this:

<input type="email" id="emailTest">

So on the form submit the Browser automaticaly validate the input

Or you can use a JavaScript Function Regex like this:

function validateEmail(email) {
var 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,}))$/;
return re.test(email);

}

Matheus Cuba
  • 2,068
  • 1
  • 20
  • 31
  • I need to code in terms of Javascript, my code will not allow your answer. How can I test for "@" symbol in Java – Joe Sep 03 '17 at 01:34
  • JavaScript and Java are two different languages. I also suggest using the HTML solution, it's more semantically correct and will check for proper email address formatting. – pixleight Sep 03 '17 at 01:40
  • Fixed to validate with JavaScript! – Matheus Cuba Sep 03 '17 at 01:41