Forum Moderators: open

Message Too Old, No Replies

Form validation troubles

form validation, name, email

         

misterm2008

4:05 pm on Feb 4, 2010 (gmt 0)

10+ Year Member



Hi

Hope everyone is warmer than me today.

I am following this tutorial at w3schools to validate a very simple form on my website:
[w3schools.com...]

The tutorial gives 2 examples, both of which I can get to work separately, but I can't get them to work together.

My form only consists of 2 field: name and email.

All i want to do is make sure the name field has been populated and the email address is valid.

I'm sure there is an easy way to get the 2 examples from w3 schools to work, but I just can't figure out the JavaScript.

Any help would be much appreciated.

Many thanks

D

misterm2008

10:13 pm on Feb 4, 2010 (gmt 0)

10+ Year Member



Figured it out myself, so if anyone else finds it useful:

<script type="text/javascript">
function validate_required(field,alerttxt)
{
with (field)
{
if (value==null||value=="")
{
alert(alerttxt);return false;
}
else
{
return true;
}
}
}
function validate_email(field,alerttxt)
{
with (field)
{
apos=value.indexOf("@");
dotpos=value.lastIndexOf(".");
if (apos<1||dotpos-apos<2)
{alert(alerttxt);return false;}
else {return true;}
}
}
function validate_form(thisform)
{
with (thisform)
{
if (validate_required(name,"Please enter your name")==false)
{name.focus();return false;}
if (validate_email(email,"Not a valid e-mail address!")==false)
{email.focus();return false;}
}
}
</script>