Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

ombrenelcielo

macrumors regular
Original poster
Jan 21, 2011
158
18
Helsinki, Finland
Hi everyone,
I needed to create a validation form to allow only 2 domains (basic check if @abd.com or @asd.com and allow those only).

It's plain javascript, can you give me some suggestions?

:confused:

as of today I do the validation like this:

PHP:
function validateForm()
{
var x=document.getElementById("user_email").value;
var atpos=x.indexOf("@thisdomain.com");
var dotpos=x.lastIndexOf(".");
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length)
  {
  alert("Please use Your @thisdomain.com email address");
  return false;
  }
}
 
Last edited by a moderator:
Here's a tweaked function that uses a regular expression to check for two domains being present. In this case the valid domains are thatdomain.com and thisdomain.com. It also ensures that there are at least 2 characters before the @ characters and no spaces anywhere. I added an else piece simply for testing purposes.

PHP:
function validateForm() {
	var x = document.getElementById("user_email").value;
	var regex = new RegExp(/^[\w\.\+_-]+[\w]+@(this|that)domain\.com$/);
	// Validate email address
	if (!regex.test(x)) {
		alert("Please use your @thisdomain.com or @thatdomain.com email address.");
		return false;
	}
	else {
		alert('Address valid.');
	}
}
 
Of course you realize that Javascript client-side validation is no validation at all, right?

It's a nicety. You still need server-side validation.
 
thanks for the infos,
I have a script running server side to clean up the domains different than the ones I want from the DB, and JS on the client side helps a bit to have more coherent data ;) :)
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.