Wednesday, August 27, 2008

Validation for Form Submission with Javascript: Textbox

There are a few common form fields that we need to validate before submit the web form.

Here is a collection of javascript code to access form field value and run some common validations.

For exmaple, you have a form named "myForm1" and you have a function to validate the form submission:

function validateSubmission()
{
// code added inside function
}

1. Text field.

This is the easiest one. Usually this section of code will be enough:
// this block of code checks if user has put in the first name.
// It will check the field value and send a warning to user when the field is empty.
// Also, it will move the cursor onto the field. So the user can type in something immediately.

var fldname="txtfirstname";
if (document.myForm1[fldname].value == ""){
alert("Please put in the first name.");
document.myForm1[fldname].focus();
return false;
}
Besides just checking if the field is empty or not, you can check if the input is correctly formatted.
Here is the sample for email validation:

function checkemail(fldname)
{
var passfail=true;
var myval=document.myForm1[fldname].value;
var mylen=myval.length;
if(mylen>0)
{
if(myval.indexOf("@")<0)
{
alert("Email must be in the format:\r\nuser@domain.com");
document.myForm1[fldname].focus();
return false;
}

if(myval.indexOf(".")<0)
{
alert("Email must be in the format:\r\nuser@domain.com");
document.myForm1[fldname].focus();
return false;
}
}
return true;
}

No comments: