/* Created by: Anita Sudhakar :: http://www.smartwebby.com/DHTML/email_validation.asp */ function echeck(str) { var at = "@"; var dot = "."; var lat = str.indexOf(at); var lstr = str.length; var ldot = str.indexOf(dot); if (str.indexOf(at) == -1) { alert("ID Email tidak valid!"); return false; } if (str.indexOf(at) == -1 || str.indexOf(at) == 0 || str.indexOf(at) == lstr) { alert("ID Email tidak valid!"); return false; } if (str.indexOf(dot) == -1 || str.indexOf(dot) == 0 || str.indexOf(dot) == lstr) { alert("ID Email tidak valid!"); return false; } if (str.indexOf(at, (lat + 1)) != -1) { alert("ID Email tidak valid!"); return false; } if (str.substring(lat - 1, lat) == dot || str.substring(lat + 1, lat + 2) == dot) { alert("ID Email tidak valid!"); return false; } if (str.indexOf(dot, (lat + 2)) == -1) { alert("ID Email tidak valid!"); return false; } if (str.indexOf(" ") != -1) { alert("ID Email tidak valid!"); return false; } return true; } function ValidateForm() { var emailID = document.frmSample.txtEmail; if ((emailID.value == null) || (emailID.value == "")) { alert("Ketik alamat email Anda!"); emailID.focus(); return false; } if (echeck(emailID.value) == false) { emailID.value = ""; emailID.focus(); return false; } return true; }
<form name='frmSample' method='post' action='#' onSubmit='return ValidateForm()'> Masukkan alamat email: <input type='text' name='txtEmail' /> <input type='submit' name='submit' value='Submit' /> </form>
Pembaharuan
Filter yang lebih sederhana dengan regex dari Dynamic Drive:
/* * Email Validation script - © Dynamic Drive (www.dynamicdrive.com) * This notice must stay intact for legal use. * Visit http://www.dynamicdrive.com/ for full source code */ var emailfilter = /^\w+[\+\.\w\-]*@([\w\-]+\.)*\w+[\w\-]*\.([a-z]{2,4}|\d+)$/ig; function checkmail(e) { var checkval = emailfilter.test(e.value); if (checkval == false) { alert("ID Email tidak valid!"); e.select(); } return checkval; }
<form name='taufik'> <input name='prikitiwform' type='text' /> <input type='submit' onClick='return checkmail(this.form.prikitiwform)' value='Submit' /> </form>
Sumber https://www.dte.web.id/