Sunday, September 28, 2008

How to handle validations using JavaScript?

There might be many validations specific to business rules adopted .For example there might be form to create user.
There will be plenty of fields where user has to enter his/her details and click on save button.
As soon as user clicks on save button, the functionality is the application should save the details to the database table. Since database designed has many constraints specified or mentioned at design level, some thing like the user name length should be 10 characters according to data base. In such case if user gives user name whose length is 11, obviously there occurs an exception while inserting record into table.
It does not look or feel good if it is thrown from database to user, where user cannot understand the message or can be a server failure exception.

Instead it could be pretty good if those design level constraints, business level rules are handled , validate the user provided data and inserting into table if it is fine else throwing appropriate messages onto user interface.

function fun_validateData(txtUsr)
{
var txtUserName =document.getElementById(txtUsr);
if(txtUserName.value.length>10)
{
alert(‘User name should be less than or equal to 10 characters’);
return false;
}
return true;

}
The above function helps in validating the data provided by user for user name whether its length is less than 10 characters.

<html>
<head></head>
<body>

<asp:TextBox ID="txtUserName" runat="server"></asp:TextBox>
<asp:Button ID="btnSave" runat="server" onclick=”btnSave_Click”/>
</body></html>

In my code behind page in page load event I shall add attributes to onlcik event of “btnSave”.

protected void Page_Load(object sender, EventArgs e)
{
btnSave.Attributes.Add("OnClick", "return fun_validateData('" + txtUserName.ClientID + "');");
}

Since I am saying “return”, so depending upon the boolean value returned from the function (fun_ValidateData) , the page gets postbacked. If the funtion returns true then the page postbacks to raise onclick event of the save button.
If the validate function returns false then the page does not post back and remains there.


Looking into the validate function defined in java script , we can find that it retruns false if the validaiton finds an error in user inputs (username length) and thus the page does not post back.
It returns true when the user input is perfect and raies on click (server) event of the save button.

No comments: