PDA

View Full Version : Javascript validate form popup



Xeonz
21-May-2008, 02:41 AM
Hey!

I have a good javascript to validate your form and get a popup.

I have tried it and it works with formail and HTML-template etc.

Here is a sample code for validate e-mail field:

PUT THIS IN HEAD:


<script type="text/javascript">
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_email(email,"Všnligen ange din mailadress korrekt!")==false)
{email.focus();return false;}
}
}
</script>

LOOK AT THIS (added onsubmit):


<form method="post" action="http://www.yoursite.se/formmail.php" onsubmit="return validate_form(this);" name="NameOnForm">

NOTE: I have added: onsubmit="return validate_form(this);"



More info:
http://www.w3schools.com/js/js_form_validation.asp


Hope this helps!

Xeonz
21-May-2008, 03:34 AM
Have a little problem myself.

Anyone who know how to edit the code if I have more than e-mail to validate?

I have tried this:


<script type="text/javascript">
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_email(email,"Všnligen ange din mailadress korrekt!")==false)
{email.focus();return false;}
}
}


function validate_required(field,alerttxt)
{
with (field)
{
if (value==null||value=="")
{alert(alerttxt);return false;}
else {return true}
}
}function validate_form(thisform)
{
with (thisform)
{
if (validate_required(telbostad,"Všnligen ange telefonnummer till din bostad.")==false)
{telbostad.focus();return false;}
}
}
</script>

The problem is that when I have one field correct the submitbutton doesnt restart the validation process?!

The form still only value one field..