Javascript Form Validation - Help

Soldato
Joined
8 Oct 2007
Posts
2,844
Hi,

I'm trying to do a simple form in HTML, with two Javascript functions, but I can't get it to work. All it's meant to do is have an alert message when the user types in an invalied email or phone number.

Here is the HTML:

Code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>ClientValidation</title>
</head>
<script type="text/javascript" src="ClientValidation.js">
</script>                
<body>
<form action="" method="get">
  <label>Name:
  <input type="text" name="Name" id="Name" />
  </label>
  <p>
    <label>Surname:
    <input type="text" name="Surname" id="Surname" />
    </label>
  </p>
  <p>
    <label>Email Address:
    <input type="text" name="Email Address" id="Email Address" />
    </label>
  </p>
  <p>
    <label>Phone Number:
    <input type="text" name="Phone Number" id="Phone Number" />
    </label>
  </p>
  <p>
    <label>
    <input type="submit" name="button 1" id="button 1" value="Submit" onclick="CheckNumber()" />
    </label>
  </p>
</form>
</body>
</html>

Javascript:

Code:
<script>
function CheckEmail()
{
    var email=document.forms[0].elements[0].value;
    var countDot=0;
    var countAt=0;
   
    for (var i=0; i<email.length; i++)
    {
        var c=email.charAt(i);
       
        if (c=='@')
        {
            countAt++;
        }
        if (c=='.'
        {                
            countDot++;
        }
    }
    if (countAt>1 || countAt==0 || countDot==0
        {
            alert ("This is not a valid email address")
            return false;
        }
    else
    {
        return true;
    }
}

function CheckNumber()
{
    var PhoneNumber=document.forms[0].elements[0].value;
   
    for (var i=0; i<PhoneNumber.length; i++)
    {
          var c=PhoneNumber.charAt(i);
          if (!(c>0 || c<9))
          {
               alert("This is not a valid Phone Number");
               return false;
          }
          else
          {
               return true;
          }
    }
}
</script>

So all I've done is added the CheckNumber function to the submit button, but something is not right, it never comes up with the alert. Is the function in the right place in the HTML?

Also, I need to use the CheckEmail function aswell to check the Email, where do I put the function? Can I have them both on the submit button.

If anyone could read over it I would appreciate it. Bear in mind I am a noob at this :P

Thanks
 
Without looking into it in too much detail, you don't need the opening and closing script tags in your .js file so it might be that.
 
Your code is also missing a couple of closing brackets on the if statements (on lines 15 and 20 once the script tags are removed). The best way to debug this sort of thing is to use Firefox and the Web developer toolbar.

A better way to handle JavaScript validation is to have a regular submit button but add your validation to the onsubmit attribute of the form element, take a quick look at this guide on w3schools:

http://www.w3schools.com/jS/js_form_validation.asp

Do post back though if that doesn't help.
 
I've removed the script tags from the .js file and added those missing brackets. Thanks. Unfortunatelly, it made no difference, can you notice anything else that is wrong?

If I can't get this to work I'll have a look at that guide.

Updated Javascript:

Code:
function CheckEmail()
{
	var email=document.forms[0].elements[0].value;
	var countDot=0;
	var countAt=0;
	
	for (var i=0; i<email.length; i++)
	{
		var c=email.charAt(i);
		
		if (c=='@') 
		{
			countAt++;
		}
		if (c=='.') 
		{ 				
			countDot++;
		}
	}
	if (countAt>1 || countAt==0 || countDot==0)
		{ 
			alert ("This is not a valid email address")
			return false;
		}
	else 
	{
		return true;
	}
}

function CheckNumber()
{
	var PhoneNumber=document.forms[0].elements[0].value;
	
	for (var i=0; i<PhoneNumber.length; i++) 
	{
          var c=PhoneNumber.charAt(i);
          if (!(c>0 || c<9))
		  { 
               alert("This is not a valid Phone Number");
			   return false;
		  }
		  else
		  {
			   return true;
		  } 
	}
}
 
I don't know if it's the cause of your problems, but both functions are looking at the same form field.

Try changing it to
Code:
document.[formname].[fieldname].value

Also, it may be worth noting that using regular expressions for this would cut that code down a hell of a lot, try this

Code:
function CheckEmail()
{
	var sEmail = document.[formname].[emailfieldname].value;
	var emailReg = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
	
	if (!emailReg.test(sEmail)) {
		alert ("This is not a valid email address")
		return false
	}
	else {
		return true
	}
}

function CheckNumber()
{
	var sPhoneNumber = document.[formname].[phonefieldname].value;
	var phoneReg = /[0-9]{6,10}/;
	
	if (!phoneReg.test(sPhoneNumber)) {
		alert ("This is not a valid phone number")
		return false
	}
	else {
		return true
	}
}
Finally, your code doesn't allow telephone numbers to have spaces or brackets in, which some people like to add.

In the past I've found that if you need to have phone numbers validated it's best to use an input mask for them
 
Last edited:
Spunkey, thanks for your efforts :)

I have tried to change the lines you mentioned, not sure if I'm doing it right, it shows a syntax error on both lines. Also, I've yet to use those expressions "-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]" etc, so I think I'll stick with this way first, no idea what they mean :p

I'm still not sure where to put the functions in the HTML either.. I only have the CheckNumber one in there atm.

Here's the code now:

HTML:

Code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>ClientValidation</title>
</head>
<script type="text/javascript" src="ClientValidation.js">
</script>                 
<body>
<form name="form1" method="get">
  <label>Name:
  <input type="text" name="field1" id="Name" />
  </label>
  <p>
    <label>Surname:
    <input type="text" name="field2" id="Surname" />
    </label>
  </p>
  <p>
    <label>Email Address:
    <input type="text" name="field3" id="Email Address" />
    </label>
  </p>
  <p>
    <label>Phone Number:
    <input type="text" name="field4" id="Phone Number" />
    </label>
  </p>
  <p>
    <label>
    <input type="submit" name="button 1" id="button 1" value="Submit" onclick="CheckNumber()" />
    </label>
  </p>
</form>
</body>
</html>

JS:

Code:
function CheckEmail()
{
	var sEmail = document.[form1].[field3].value;
	var countDot=0;
	var countAt=0;
	for (var i=0; i<email.length; i++)
	{
		var c=email.charAt(i);
		if (c=='@') 
		{
			countAt++;
		}
		if (c=='.') 
		{ 				
			countDot++;
		}
	}
	if (countAt>1 || countAt==0 || countDot==0)
		{ 
			alert ("This is not a valid email address")
			return false;
		}
	else 
	{
		return true;
	}
}

function CheckNumber()
{
	var sPhoneNumber = document.[form1].[field4].value;
	for (var i=0; i<PhoneNumber.length; i++) 
	{
          var c=PhoneNumber.charAt(i);
          if (!(c>0 || c<9))
		  { 
                           alert("This is not a valid Phone Number");
			   return false;
		  }
		  else
		  {
			   return true;
		  } 
	}
}
 
Almost there :)

First off the form references shouldn't have the square brackets -
Code:
var sEmail = document.form1.field3.value;

Secondly, I'd make your two functions into one that checks both fields. The best way to call it is by using this method...
Code:
// JS
function testValid() {
  // check the email field
  // check the phone field

  // return true or false
}

Code:
<form name="form1" method="get" action="mypage.php" onsubmit="return testValid();">
  <!-- YOUR FORM -->
  <input type="submit" value="Submit" />
</form>
 
Thanks again, I've removed the brackets on the form references and tried to merge the function into one. Here's what I have:

HTML:

Code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>ClientValidation</title>
</head>
<script type="text/javascript" src="ClientValidation2.js">
</script>                 
<body>
<form name="form1" method="get" action="" onsubmit="return testValid();">
  <label>Name:
  <input type="text" name="field1" id="Name" />
  </label>
  <p>
    <label>Surname:
    <input type="text" name="field2" id="Surname" />
    </label>
  </p>
  <p>
    <label>Email Address:
    <input type="text" name="field3" id="Email Address" />
    </label>
  </p>
  <p>
    <label>Phone Number:
    <input type="text" name="field4" id="Phone Number" />
    </label>
  </p>
  <p>
   <input type="submit" value="Submit" />
</form>
</body>
</html>

JS:

Code:
function testValid()
{
	var sEmail = document.form1.field3.value;
	var countDot=0;
	var countAt=0;
	for (var i=0; i<email.length; i++)
	{
		var c=email.charAt(i);
		if (c=='@') 
		{
			countAt++;
		}
		if (c=='.') 
		{ 				
			countDot++;
		}
	}
		if (countAt>1 || countAt==0 || countDot==0)
		{ 
			alert ("This is not a valid email address")
			return false;
		}
	var sPhoneNumber = document.form1.field4.value;
	for (var i=0; i<PhoneNumber.length; i++) 
	{
          var c=PhoneNumber.charAt(i);
          if (!(c>0 || c<9))
		  { 
               alert("This is not a valid Phone Number");
			   return false;
		  }
		  else
		  {
			   return true;
		  } 
	}
}

Something still not right, must be very close though. Is the function correct? :)
 
Unless I'm missing something sPhoneNumber and PhoneNumber and sEmail and email aren't the same!
Code:
var sEmail = document.form1.field3.value;
	var countDot=0;
	var countAt=0;
	for (var i=0; i<email.length; i++)

either loose the s and change the E to lower case or change the other instances of email to sEmail

oh and the weird string is a regular expression. They make validation easy once you understand them.
 
Last edited:
Unless I'm missing something sPhoneNumber and PhoneNumber and sEmail and email aren't the same!

Ah, didn't notice that >.<

Ok, changed that, and i'm getting somewhere. However, there must be some error in the function, because it's not working right.

If I type nothing at all in the fields and press submit, I get the alert "This is not a valid email address"

No matter what I type in the Phone Number field, I still get the alert "This is not a valid email address"

If I type in a valid Email Address however, I get no alerts.

Any ideas?

JS:
Code:
function testValid()
{
	var Email = document.form1.field3.value;
	var countDot=0;
	var countAt=0;
	for (var i=0; i<Email.length; i++)
	{
		var c=email.charAt(i);
		if (c=='@') 
		{
			countAt++;
		}
		if (c=='.') 
		{ 				
			countDot++;
		}
	}
		if (countAt>1 || countAt==0 || countDot==0)
		{ 
			alert ("This is not a valid email address")
			return false;
		}
	var PhoneNumber = document.form1.field4.value;
	for (var i=0; i<PhoneNumber.length; i++) 
	{
          var c=PhoneNumber.charAt(i);
          if (!(c>0 || c<9))
		  { 
               alert("This is not a valid Phone Number");
			   return false;
		  }
		  else
		  {
			   return true;
		  } 
	}
}
 
It will only show the first alert as the return false statement stops the function there and then and doesn't run any other part of it.

firstly you didn't change the variable email.charAt to Email.charAt at the top.

You also need to change the bottom bit to

Code:
var PhoneNumber = document.form1.field4.value;
	var validPhone = true;
	if (PhoneNumber.length ==0)
	{ 
		alert("Phone number is required");
	     validPhone = false;
	}
	
	for (var i=0; i<PhoneNumber.length; i++) 
	{
          var c=PhoneNumber.charAt(i);
          if (!(c>0 || c<9))
		  { 
               alert("This is not a valid Phone Number");
			   validPhone = false;
			   break;
		  }
	}
	return validPhone;

as you were accepting the first letter of the phone number as full proof that the rest was fine.
 
Last edited:
Thanks Simon :)

The email part seems to work now, great. There is just one problem left, if I put in a valid email but not a valid phone number, I don't get an alert about the phone number. Why would that be?

JS:

Code:
function testValid()
{
	var Email = document.form1.field3.value;
	var countDot=0;
	var countAt=0;
	for (var i=0; i<Email.length; i++)
	{
		var c=Email.charAt(i);
		if (c=='@') 
		{
			countAt++;
		}
		if (c=='.') 
		{ 				
			countDot++;
		}
	}
		if (countAt>1 || countAt==0 || countDot==0)
		{ 
			alert ("This is not a valid email address")
			return false;
		}
	var PhoneNumber = document.form1.field4.value;
	var validPhone = true;
	if (PhoneNumber.length ==0)
	{ 
		alert("Phone number is required");
	     validPhone = false;
	}
	
	for (var i=0; i<PhoneNumber.length; i++) 
	{
          var c=PhoneNumber.charAt(i);
          if (!(c>0 || c<9))
		  { 
               alert("This is not a valid Phone Number");
			   validPhone = false;
			   break;
		  }
	}
	return validPhone;
}
 
This is the entire code I have which works:
Code:
<html>
<head>
<script>
function testValid()
{

	var Email = document.form1.field3.value;
	var countDot=0;
	var countAt=0;
	for (var i=0; i<Email.length; i++)
	{
		var c=Email.charAt(i);
		if (c=='@') 
		{
			countAt++;
		}
		if (c=='.') 
		{ 				
			countDot++;
		}
	}

	if (countAt>1 || countAt==0 || countDot==0)
	{ 
		alert ("This is not a valid email address")
		return false;
	}

	var PhoneNumber = document.form1.field4.value;
	var validPhone = true;
	if (PhoneNumber.length ==0)
	{ 
		alert("Phone number is required");
	     validPhone = false;
	}
	
	for (var i=0; i<PhoneNumber.length; i++) 
	{
          var c=PhoneNumber.charAt(i);
          if (!(c>0 || c<9))
		  { 
               alert("This is not a valid Phone Number");
			   validPhone = false;
			   break;
		  }
	}
	return validPhone;

}
</script>
</head>
<body>
<form name="form1" id="form1">
Email<input type="text" id ="field3" value="[email protected]"></input><br>
Phone<input type="text" id ="field4"></input><BR>
<input type="Button" onclick="javascript:testValid()" value="test">
</form>
</body>
</html>
 
Hey Simon, I tried the code you used to test, it does the same as mine.

The Email validation works. It comes up with an alert if it's invalid, nothing if it's valid.

The blank Phone number field part works. It comes up with an alert if the field is empty.

The Invalid Phone Number part does NOT work. It doesn't come up with an alert if I type a invalid phone number.

Can you test this for yourself? I can't work out why. Cheers :)
 
Works for me in IE and firefox.

email blank, phone blank = invalid email
email OK, phone blank = phone number required
email OK, phone abcd = this is not a valid phone number
email OK, phone 1234 = nothing
email blank or wrong, phone 1234 = this is not a valid email address

Anyone else having a problem?

edit although
email OK, phone a space = no error

Code:
 var c=PhoneNumber.charAt(i);
          if (!(c>0 || c<9) || (c==" "))
 
Last edited:
ok seems to be working fine now :) Thanks

One last thing, I want to make the error message for phone number appear directly under the field instead of an alert box. Can anyone explain how to do this?
 
put a place holder (span,div,label) on the page where you want the message to appear. and instead of the alert do something like
document.getElementById("telMsg").innerHTML = "Invalid Telephone Number"
 
put a place holder (span,div,label) on the page where you want the message to appear. and instead of the alert do something like
document.getElementById("telMsg").innerHTML = "Invalid Telephone Number"

Worked, thanks :) And thanks to everyone else too, I think I'm done here, for now :p
 
Back
Top Bottom