Thursday, November 20, 2008

Validator Controls In ASP.Net

In ASP.NET we have 5 validator controls they are:



1)The RequiredFieldValidator Control



2)The CompareValidator Control



3)The RangeValidator Control



4)The RegularExpressionValidator Control



5)The CustomValidator Control





1)RequiredFieldValidator- This is used when the user has to enter compulsarily in the field specified.It should not be left empty.The syntax is



asp:TextBox ID="txtbox1" runat="server"



asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate="txtbox1" ErrorMessage="TextBox cannot be left empty" Display="dynamic"



Here ErrorMessage will be displayed when the user does not enter anything in the requiredfield control, for ControlToValidate we should give the control name we want to validate, Display dynamic means that the validation error message will be displayed dynamically while submitting the form,ID is given for identifying the requiredfieldvalidator control.





2)CompareValidator- This is used when we have a requirement like comparing two textboxes values.The syntax is



asp:Textbox ID="txtbox1" runat="server"



asp:Textbox ID="txtbox2" runat="server"



asp:CompareValidator ID="CompareValidator1" runat="server" ControlToValidate="txtbox1"
ControlToCompare="txtbox2" Operator="LessThan" Type="Integer" ErrorMessage="txtbox1 value should be less than txtbox2 value" Display="dynamic"


Here Errormessage will be displayed dynamically and will be shown to the user when the conditions voilates,ControlToValidate we should give one field and ControlToCompare we should give other field which we want to compare,Operator means on which condition do you want to compare the 2 fields in a page like equal,lessthan,notequal,greaterthan etc., Type specifies the output should be of which type.


3)RangeValidator Control-This is used for restricting the value of a field from minimun value to maximum value.The syntax is

asp:textbox id="txtbx1" runat="server"

asp:button id="btn1" runat="server" text="Submit"


asp:RangeValidator ID="RangeValidator1" runat="server" ControlToValidate="txtbx1" MinimumValue="01-01-2007" MaximumValue="01-01-2005" ErrorMessage="Please enter a date within the 2007"(This message will be displayed if text property is not set) Text="Enter valid date"(Message to displayed when validation fails) Type="Date"

Here If the textbox entered date is valid(between the range of the minimun and maximum value given) then in the button click no errer messasge is displayed.If the value crosses the range mentioned in the validator then error message or the text is diaplayed.acording to the trype mentioned we can do the range validation like in our example it is date but we have many like -"Currency,Double,Integer,String".We dont need to type both error message and text ,either one will be enough.The coolest part of it is that the validator will respond even if the date is invalid like "31-02-2007" (we dont have 31 days in the month of feb)

Note: The blue color is for understanding purpose not there in the code.

4)RegularExpressionValidator Control-The RegularExpressionValidator control is used to ensure that an input value matches a specified pattern,the syntax is as follows

asp:textbox id="txtbox1" runat="server"

asp:RegularExpressionValidator id="Regular Expressionvalidator1" runat="server" ControlToValidate="txtbox1" Display="Dynamic" ErrorMessage="The Zip code must be 5 numeric digits" ValidationExpression="\d{5}"

Here the validator make sure that the user will enter only 5 numeric digits only else the error message is displayed. "\d{5}" means 'd' for digits and 5 means only 5 digits will be entered.

5)CustomValidator Control-The CustomValidator control allows you to write a method to handle the validation of the value entered.The developer will develop this validator control.

In .aspx page-

asp:textbox id="txtName" runat="server"

asp:CustomValidator ID="cvName" ControlToValidate="txtName" runat="server" ErrorMessage="Country with this name already exists.Please choose another name" Display="Dynamic" OnServerValidate="cvName_ServerValidate"

In aspx.cs-


protected void cvName_ServerValidate
(object source, ServerValidateEventArgs args)
{
CountryDao cdao = new CountryDao();
if (cdao.IsCountryNameExists(txtCName.Text.Trim(),null))
{
args.IsValid = false;
}
else
{
args.IsValid = true;
}
}

Here IsCountryNameExists() is a method in the CountryDao

In CountryDao-

public bool IsCountryNameExists
(string countryName, int? countryId)
{
bool isExists = true;
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
try
{
DataSet countryDs = new DataSet();
conn.Open();
SqlCommand cmd = new SqlCommand("prcCheckCountryExists", conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter("@CountryName", DbType.String));
cmd.Parameters.Add(new SqlParameter("@CountryId", DbType.Int32));
cmd.Parameters["@CountryName"].Value = countryName;
cmd.Parameters["@CountryId"].Value = countryId;
SqlDataAdapter sqlDataAdapter = new SqlDataAdapter(cmd);
sqlDataAdapter.Fill(countryDs);
if (countryDs != null)
{
DataTable countryTb = countryDs.Tables[0];
foreach (DataRow countryRow in countryTb.Rows)
{
isExists = bool.Parse(countryRow["ISExists"].ToString());
}
}
}
catch (SqlException elex)
{
throw elex;
}
catch (Exception ex)
{
throw ex;
}
finally
{
conn.Close();
}
return isExists;
}

Here prcCheckCountryExists is a stored procedure in the sqlserver which will check whether the country name added by the user is already existing in the database,if exists then error message will be displayed and if not existing that country name will be added in the database. In the manner we can code according to our requirement using the CustomValidator control.

No comments: