Hi all,

I have form validation working well. The following is how i currently validate emails.

My question is how can i amend to validate it as an email?

if(""==document.forms.fa.user_email.value)
{
alert("Please enter an email address.");
return false;
}

I have found this following script but my javascript syntax is not up to scratch

function validate(form_id,email) {
   var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
   var address = document.forms[form_id].elements[email].value;
   if(reg.test(address) == false) {
      alert('Invalid Email Address');
      return false;
   }
}

Dani AI

Generated

The original check only tests for an empty string; actual email validation needs more care. Posts by and show two common approaches — client-side regex and service allowlists — but both have pitfalls: the thread's regex limits TLD length and omits many valid local-part characters, and the allowlist approach is brittle as new providers and subdomains appear.

Prefer a pragmatic, layered approach:

  • Let the browser do basic syntax checks with HTML5 type="email" and the Constraint Validation API.
  • Fall back to a simple client-side sanity check for user feedback (no attempt to fully implement RFC 5322).
  • Always validate and verify server-side (syntax + optional MX check + confirmation email).

Example: browser-level check with a lightweight JS fallback

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

<script>
var e = document.getElementById('email');
if (!e.checkValidity()) {
  alert('Please enter a valid email address');
}
</script>

Minimal, pragmatic client-side test (avoids an over‑strict regex)

function isLikelyEmail(value) {
  if (!value) return false;
  if (value.indexOf('@') === -1) return false;
  if (/\s/.test(value)) return false;
  var parts = value.split('@');
  if (parts.length !== 2 || parts[0].length === 0 || parts[1].indexOf('.') === -1) return false;
  return true;
}

Troubleshooting notes: ’s example inverts match logic and uses a global regex flag; using /g with repeated .test() calls can give surprising results — prefer a non-global regex or simple string checks (MDN explains RegExp.test behavior). Avoid hard-coding allowed providers as in ’s approach; use server-side verification and a confirmation email for real assurance. For authoritative background on email syntax see RFC 5322 and use server-side validators like PHP’s filter_var() for final checks (MDN input=email, RFC 5322, PHP filter_var).

Recommended Answers

All 3 Replies

Hi all,

I have form validation working well. The following is how i currently validate emails.

My question is how can i amend to validate it as an email?

if(""==document.forms.fa.user_email.value)
{
alert("Please enter an email address.");
return false;
}

I have found this following script but my javascript syntax is not up to scratch

function validate(form_id,email) {
   var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
   var address = document.forms[form_id].elements[email].value;
   if(reg.test(address) == false) {
      alert('Invalid Email Address');
      return false;
   }
}

pass the id of the appropriate field where the email is entered.

function validate(textFieldId)
{
	//regex for email validation
	var regex = new RegExp("^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$", 'g');
	//test if the regex match
	if(document.getElementById(textFieldId).value.match(regex))
        {
                alert("Invalid email adress");
                return false;
        } else { return true; }
}

Didn't test this out, but this should work, or be close to solution, hope it helps :)

Here's another solution, I use this and now works great

Description:
1. Check only if is mail.
CheckMail('', '-1')
Will be checked if is mail (string @ string . string)

2. Check if is mail and if the mail service of the mail is allowed
CheckMail('', arrayOfAllowedServices)

// Array of allowed mail services
var services = new Array();
services[0] = "gmail"
services[1] = "yahoo"
services[2] = "hotmail"
CheckMail('testname@testservice.com', services)
// Will be checked if is mail (string @ string . string) and if the entered mail service is allowed.
// JavaScript Document - validator.js
 
/*
	@Author SkyDriver - Damjan Krstevski
	@Country/City: Macedonia, Skopje
	@Date 27/2/2010 - 7:33 AM
	@Description: Validation library...
	@License: Freeware, you can use, change and redistributed this library.
*/

/// <summary> Validate e-Mail address and e-Mail service </summary>
/// <param name="mail"> The e-Mail for validation </param>
/// <param name="allow"> Allowed e-Mail services (If allow = "-1" then all servies will be allowed) </param>
/// <api> CheckMail('testaddress@testservice.com', '-1'); </api>
function CheckMail(mail, allow) {
	try {
		if(mail.indexOf("@") != -1) {
			var len = mail.length;
			var index = mail.indexOf("@");
			if(len > index) {
				var tmp = mail.substring(index + 1, len);
				if(tmp.indexOf(".") != -1 && tmp.substring(tmp.indexOf(".")+1, tmp.length).length > 1) {
					if(allow != "-1") {
						var service = tmp.substring(0, tmp.indexOf("."));
						var arLen = allow.length;
						for(var i=0; i<arLen; i++) {
							if(service == allow[i]) {
								return true;	
							}
						}
						alert("You entered e-Mail address with invalid service!");
						return false;
					} else {
						return true;
					}
				} else {
					alert("You entered e-Mail address with invalid service!");
					return false;
				}
			} else {
				alert("You entered invalid e-Mail address!");
				return false;
			}
		} else {
			alert("Your e-Mail is not a valid!");	
			return false;
		}
	} catch (e) {
		alert("An error occurred.\nDetails: " + e);
		return false;
	}
}

Hi all,

I have form validation working well. The following is how i currently validate emails.

My question is how can i amend to validate it as an email?

if(""==document.forms.fa.user_email.value)
{
alert("Please enter an email address.");
return false;
}

I have found this following script but my javascript syntax is not up to scratch

function validate(form_id,email) {
   var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
   var address = document.forms[form_id].elements[email].value;
   if(reg.test(address) == false) {
      alert('Invalid Email Address');
      return false;
   }
}

above code is right.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.