JavaScript: Email Validation (pt. 1)

Tech: JavaScript

Challenge: validating emails for a POST form… regex is always painful… what is best practice? I believe this is an incredibly easy & fast choice. Note, not my code but I will be using it everywhere!

Code (drop in <head>):

<script>

function validateForm() {

var x = document.forms[“myForm”][“email”].value;

var atpos = x.indexOf(“@”);

var dotpos = x.lastIndexOf(“.”);

if ( atpos < 1 || dotpos < atpos + 2 || dotpos + 2 >= x.length ) {

alert(“Not a valid e-mail address!”);

return false;

}

<script>

 

For the form:

<form name=”myForm” onsubmit=”return validateForm()”>

Email: <input type=”text” name=”email>

</form>

 

Source:

https://www.w3schools.com/js/tryit.asp?filename=tryjs_form_validate_email