Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Language: Web
Expertise: Beginner
Mar 14, 2000

Validate Form Input on the Client Side

If you are developing Web pages that provide HTML forms to the user, then you may notice that many times invalid data gets submitted. To reduce such invalid input, you can easily implement some basic validation at the client side. This way you will save some extra hits to the Web server. For example, if your Web page contains a login dialog, then you can easily check for the minimum length of the login or certain invalid characters in the login string.

Here is a sample HTML page that contains a login form that validates at the client side for the minimum number of characters in a login and password string. From the "ONCLICK()" event of the OK button, the Validate() method is called, which then calls the submit method of the form if the login information is correct.

 
<HTML>
<HEAD>
<TITLE>Form Validation Demo</TITLE>
</HEAD>
<BODY>
<FORM ACTION="MyProcess.asp" 
METHOD=POST NAME="LoginForm">
<TABLE ALIGN=left BORDER=0 CELLSPACING=0 
CELLPADDING=0>
<TR><TD>Login:</TD>
<TD><INPUT TYPE="TEXT" MAXLENGTH="10" NAME="Login"></TD>
</TR>
<TR><TD>Password:</TD>
<TD><INPUT TYPE="PASSWORD" 
MAXLENGTH="10" NAME="Passwd"></TD>
</TR>
<TR><TD><INPUT TYPE="BUTTON" 
Value="OK" NAME="OK"
ONCLICK="Validate()"></TD>
</TR></TABLE>
</FORM>

<SCRIPT LANGUAGE="JavaScript">
function Validate()


var bValid = true, strErr = "", newline = "\n";

if (document.LoginForm.Login.value.length < 4) {
 strErr = "Login name cannot be less than 4 characters.";
 bValid = false;
 document.LoginForm.Login.focus();
}
if (document.LoginForm.Passwd.value.length < 4){
 strErr = strErr + newline +
   "Password cannot be less than 4 characters.";
 bValid = false;
 document.LoginForm.Passwd.focus();
}
if (bValid == true)
  document.LoginForm.submit();
else
  alert(strErr);
}
</SCRIPT>
</BODY>
</HTML>
Deepak Pant
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap
Thanks for your registration, follow us on our social networks to keep up-to-date