PDA

View Full Version : Form Validation is Killing Me!!!


demonseed
09-04-2002, 11:20 AM
Hi everyone.

I have a simple form, with two fields only, for Email and Password and an image as a link to submit the form.

All I want to do is to be able to validate the Email address on submission so it must contain a@a. (1 char before @, an @, one char after @ and a .)

The Password needs to be validated to be only Alphanumeric and contain 6 - 10 characters.

If a field is incorrect I would like an Alert box displaying what is wrong and the focus set back to the 'bad' field.

Here's my form code:

<form name="Login" method="get">

E-Mail Address:

<input type="text" name="EMail" maxlength="43" size="16">

Password:<br>

<input type="password" name="Pass" maxlength="10" size="7" onUnFocus="javascript:document.Login.submit();"><br>

<a href="javascript:document.Login.submit();"><img src="images/login.gif" width="41" height="15" border="0" hspace="5" vspace="10" align="middle"></a>

</form>


I found a cut & paste example on About.com which validates Name, email address and , it works fine for the explicit HTML form code they provide, but I can't get it to work for my form.

They're code is as follows:

<script Language="JavaScript">

function isEmailAddr(email)
{
var result = false;
var theStr = new String(email);
var index = theStr.indexOf("@");
if (index > 0)
{
var pindex = theStr.indexOf(".",index);
if ((pindex > index+1) && (theStr.length > pindex+1))
result = true;
}
return result;
}

function validRequired(formField,fieldLabel)
{
var result = true;

if (formField.value == "")
{
alert('Please enter a value for the "' + fieldLabel +'" field.');
formField.focus();
result = false;
}

return result;
}

function allDigits(str)
{
return inValidCharSet(str,"0123456789");
}

function inValidCharSet(str,charset)
{
var result = true;

// Note: doesn't use regular expressions to avoid early Mac browser bugs
for (var i=0;i<str.length;i++)
if (charset.indexOf(str.substr(i,1))<0)
{
result = false;
break;
}

return result;
}

function validEmail(formField,fieldLabel,required)
{
var result = true;

if (required && !validRequired(formField,fieldLabel))
result = false;

if (result && ((formField.value.length < 3) || !isEmailAddr(formField.value)) )
{
alert("Please enter a complete email address in the form: yourname@yourdomain.com");
formField.focus();
result = false;
}

return result;

}

function validNum(formField,fieldLabel,required)
{
var result = true;

if (required && !validRequired(formField,fieldLabel))
result = false;

if (result)
{
if (!allDigits(formField.value))
{
alert('Please enter a number for the "' + fieldLabel +'" field.');
formField.focus();
result = false;
}
}

return result;
}


function validInt(formField,fieldLabel,required)
{
var result = true;

if (required && !validRequired(formField,fieldLabel))
result = false;

if (result)
{
var num = parseInt(formField.value);
if (isNaN(num))
{
alert('Please enter a number for the "' + fieldLabel +'" field.');
formField.focus();
result = false;
}
}

return result;
}


function validDate(formField,fieldLabel,required)
{
var result = true;

if (required && !validRequired(formField,fieldLabel))
result = false;

if (result)
{
var elems = formField.value.split("/");

result = (elems.length == 3); // should be three components

if (result)
{
var month = parseInt(elems[0]);
var day = parseInt(elems[1]);
var year = parseInt(elems[2]);
result = allDigits(elems[0]) && (month > 0) && (month < 13) &&
allDigits(elems[1]) && (day > 0) && (day < 32) &&
allDigits(elems[2]) && ((elems[2].length == 2) || (elems[2].length == 4));
}

if (!result)
{
alert('Please enter a date in the format MM/DD/YYYY for the "' + fieldLabel +'" field.');
formField.focus();
}
}

return result;
}

function validateForm(theForm)
{
// Customize these calls for your form

// Start ------->
if (!validRequired(theForm.fullname,"Name"))
return false;

if (!validEmail(theForm.email,"Email Address",true))
return false;

if (!validDate(theForm.available,"Date Available",true))
return false;

if (!validNum(theForm.yearsexperience,"Years Experience",true))
return false;
// <--------- End

return true;
}
</script>

<form method="post" action="blformvalidate.htm" onsubmit="return validateForm(this)" id=form1 name=form1>
<p>Name: <input name="fullname" size="32" ><br>
Email Address: <input name="email" size="32" ><br>
Date Available: <input name="available" size="16" ><i>(mm/dd/yyyy)<br>
</i>Years of Experience: <input name="yearsexperience" size="4" ></p>
<p><input type="submit"
value="Submit" name="submit"></p>
</form>


I'm really trying to learn JavaScript but this bit is defeating me - big time!

Thanks in advance

Matt

wap3
09-04-2002, 11:38 AM
Try:

function validateEMail() {

var em = /^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/

if (!em.test(Login.EMail.value)) {
alert("Please enter a valid email address e.g \"yourname@hotmail.com\"")
Login.EMail.focus()
return false
}


Then change your submit button code line to:

<a href="javascript:validateEMail();"><img src="images/login.gif" width="41" height="15" border="0" hspace="5" vspace="10" align="middle"></a>

demonseed
09-04-2002, 11:59 AM
When it checks and finds an error it reloads the page and writes false to the document. changing return to true writes true and sticking a ; at the end makes no difference either.

So I can't have that.

Also, How do I make it submit the form if there's not an error?

Thanks a lot

Matt

wap3
09-04-2002, 12:07 PM
I used it and it never printed errors like that, try:

function validateEMail() {

var em = /^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/

if (!em.test(Login.EMail.value)) {
alert("Please enter a valid email address e.g \"yourname@hotmail.com\"")
Login.EMail.focus()
return false
}
document.Login.submit()
return true
}

Then you need you to tell it what to do in your form tag, e.g if your running a cgi script put the following:

<form name="Login" method="POST" action="/cgi-bin/processform.cgi">

demonseed
09-04-2002, 12:18 PM
I changed it to this:

function validateEMail() {

var em = /^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/

if (!em.test(Login.EMail.value)) {
alert("Please enter a valid email address e.g \"yourname@hotmail.com\"")
document.Login.EMail.focus()

}
else document.Login.submit()
}


And it workd perfectly.


Thank you very much for your help.

Ahh, what about the password bit that needs to be between 6 and 10 chars.

I tried this:
[code]
var pass = document.Login.Pass.value
if pass.length <6 || >10 {
alert etc
}

but it said there were errors on the page.

Matt

wap3
09-04-2002, 12:28 PM
Not tested this so just try and see:

var pa = /^([0-9]{6,10})$/

if (!pa.test(Login.Pass.value)) {
alert("Please enter a valid password")
document.Login.Pass.focus()

}

P.S You did say for numbers only didn't you, well this should allow betweeen 6 and 10 numbers

demonseed
09-04-2002, 12:34 PM
it checks the first time and says invalid password, but after that it says error on the page and wont do it.

also, your code only allows for numbers... can you change this to alphanumerics?

matt

wap3
09-04-2002, 12:43 PM
Ok i have checked this in I.E and it works fine,

function validateEMail() {

var em = /^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/
var pa = /^([a-zA-Z0-9]{6,10})$/

if (!em.test(Login.EMail.value)) {
alert("Please enter a valid email address e.g \"yourname@hotmail.com\"")
document.Login.EMail.focus()
}
else if (!pa.test(Login.Pass.value)) {
alert("Please enter a valid password")
document.Login.Pass.focus()
}
else document.Login.submit()
}

Hope it works

demonseed
09-04-2002, 12:50 PM
It works perfectly.

Do you think you could explain the code for me.

What do these lines do (well I can tell) but how do they do it?

var em = /^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/
var pa = /^([a-zA-Z0-9]{6,10})$/


and this line:

if (!em.test(Login.EMail.value))


Where did the test property come from?

Thanks a bunch

Matt

PS You're THE dude!

wap3
09-04-2002, 12:58 PM
Hey, your welcme

Glad I could help

var em = /^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/
var pa = /^([a-zA-Z0-9]{6,10})$/

These are what you call regular expressions

Take the second one for example this is checking your password field to see if it contains between 6 and 10 letters and numbers only.

(a-zA-Z0-9) checks if it is numbers and letters
{6,10} checks to see if there are between 6 and 10 of the previous set, i.e. numbers and letters

You follow ??

The this line of code

if (!em.test(Login.EMail.value))

is testing the EMail field in your form to see if it matches the criteria set in the regular expression. Notice the '!' at the start, this means 'not'. So its saying if the Email field does not match the criteria then do whatever ....

:thumbsup:

aclsact
10-10-2002, 12:14 AM
Awesome explanation!! I've been looking for something like this for over a week!!

How would you look for a special character? For example, if a password required 1 special char, 1 number and 1 alpha. Figured out everything but the special char.

Thanks a bunch!!