Validation Controls in the browser before the form is submitted to the serve

Validation Controls in the browser before the form is submitted to the server

Validation Controls

These controls are used for validating controls in the browser before the form is submitted to the server

BaseValidator

It is the parent of all the validation controls.

Validation Controls inherited from BaseValidator control are:

RequiredFieldValidator, RangeValidator, CompareValidator, RegularExpressionValidator, CustomValidator.

Properties of BaseValidator:

ControlToValidate, ErrorMessage, Text, Display (Static/Dynamic/None), SetFocusOnError, ToolTip, EnableClientScript (to disable client side validations), ValidationGroup

ValidationSummary

Is used to display the collection of error message on the page at a given location. It shows the ErrorMessage property of all the controls whose validation has failed.

Properties: ShowMessageBox, ShowSummary: – any one of these two properties must be set to true.

Sample:

 

RequiredFieldValidator

To ensure that the user does not skip an entry in the control with which is it associated.

Properties: InitialValue

Example1:

 

Example2: Demo Textbox value can be anything other than the text – “Demo”

 

Example3: User will be forced to select a value other than (Select One)

 

CompareValidator

1. Comparing ValueofControl with the value of another control – ControlToCompare

2. To compare what a user has entered against a constant value – ValueToCompare

3. Value should be particular type only.- DataTypeCheck

Property: ValueToCompare, ControlToCompare, Type (String, Integer, Double, Date, Currency),

Operator (EqualTo, LessThan….DataTypeCheck)

Example1: Confirm Password must be same as password.

Password: <asp:TextBox ID=”txtPassword” runat=”server”></asp:TextBox>

<asp:RequiredFieldValidator ID=”rfvPassword” runat=”server” ControlToValidate=”txtPassword” Display=”Dynamic”

ErrorMessage=”Please provide the value for Password” Text=”Required”></asp:RequiredFieldValidator>

Confirm Password <asp:TextBox ID=”txtConfirmPassword” runat=”server”></asp:TextBox>

<asp:CompareValidator ID=”cvConfirmPassword” runat=”server” ControlToCompare=”txtPassword”

ControlToValidate=”txtConfirmPassword” Display=”Dynamic” Operator=”Equal” Type=”String”

ErrorMessage=”The Password and Confirm Password must be same” Text=”Must be same as Password”/>

Note: With one Server Control we can have more than one validation control associated but the same validation control cannot be associated with multiple server controls.

Example2: Date of Birth must be less than todays date.

 

In Page_Load :

cvDOB.ValueToCompare = DateTime.Now.ToShortDateString();

Example3: Amount must be currency (a value with max of two digits after decimal point)

 

Note: In the above example we have not set ControlToCompare and ValueToCompare

RangeValidator

Checks that a users entry is between lower and upper boundaries.

Properties: MinimumValue, MaximumValue, Type

Example:Age must be between 18 and 40:

 

RegularExpressionValidator

It Checks the users entry matches a pattern defined by a regularexpression.

Properties: ValidationExpression

Example: Must enter a valid email id.

 

ValidationExpression=”\w+([-+.’]\w+)*@\w+([-.]\w+)*\.\w+([- .]\w+)*” />

Note: RegEx is the class to work with Regular Expressions in MS.NET.

Custom Validator

Checks the user’s entry using validation logic that you write yourself.

Properties: ClientValidationFunction, ValidateEmptyText Event: ServerValidate

Example: The value must be odd number

<head>

<script language=”javascript”>

function IsOdd(src, args) //src is reference to ValidationControl.

{

if (isNaN(args.Value) || args.Value % 2 == 0)

{

args.IsValid = false; //The value provided is not valid

src.errormessage = args.Value + ” is not an odd number”

}

} Note: Value and IsValid are case sensitive…

</script>

</head>

Enter Odd Number: <asp:TextBox ID=”txtOddValue” runat=”server”></asp:TextBox>

<asp:CustomValidator ID=”cvOddValue” runat=”server” ErrorMessage=”Please provide an Odd number”

ClientValidationFunction=”IsOdd” OnServerValidate=cvOddNumber_ServerValidate

ControlToValidate=”txtOddValue“></asp:CustomValidator>

Note: If Javascript is disabled on Client/Browser, for validation Custom Validator, the server event “ServerValidate” must be handled.

protected void cvOddNumber_ServerValidate(object source, ServerValidateEventArgs args)

{

int n;

if (!int.TryParse(args.Value,out n))

args.IsValid = false;

else if (n % 2 == 0)

args.IsValid = false;

else

args.IsValid = true;

}

Additional Features

1. To skip validation if submit button is clicked

<asp:Button ID=”btnSave” runat=”server” Text=”Save” OnClick=”btnSave_Click” />

<asp:Button ID=”btnCancel” runat=”server” Text=”Cancel” CausesValidation=”False” /><br />

Note: If Cancel button is clicked the form is submitted to server with out doing any client side validation because its

CausesValidation= “False”

2. Grouping of Controls (ValidationGroup Property)

In one webform (aspx page) we can have only one server side form tag.

ValidationGroup Property: Is used to group all the validation control into a single group. A form can have more than one group of controls and based on the group of the button clicked, only controls in given group are validated.

Example:

<asp:ValidationSummary ID=”ValidationSummary2″ runat=”server” ValidationGroup=”g1“/>

Name: <asp:TextBox ID=”txtName” runat=”server” ValidationGroup=”g1“/ >

<asp:RequiredFieldValidator ID=”rfvName” runat=”server”

ControlToValidate=”txtName” ErrorMessage=”Please provide the value for txtName”

ValidationGroup=”g1“/>

<asp:Button ID=”btnSave” runat=”server” Text=”Save” ValidationGroup=”g1” />

3. To show Text of all the validation controls when the page is rendered.

protected void Page_Load(object sender, EventArgs e)

{

if (!IsPostBack)

{

Page.Validate(“”);//Validates all the validation controls on the page

ValidationSummary1.Style[“display”] = “none”; //It does not display the ErrorMessages for the first time.

}

}

4. To handle situation where client side javascript is disabled.

protected void btnSave_Click(object sender, EventArgs e)

{

if (!Page.IsValid) //validation is done on server. This is needed if the browser doesn’t support javascript.

return;

//Write here code for taking data from controls and using for what ever purpose it might be for.

Response.Write(“Data taken from controls and saved…”);

}

Notes:

  • Page.IsValid checks for only those validation controls whose GroupName is same as GroupName of the Button clicked to submit the form.

  • Page.Validators – It’s a collection of all validatoion controls in that page.

  • We can disable the validation control if we don’t want them to work on both client and server side (Enabled = “False”)

  • The Server Controls which can be validated using Validation Controls are TextBox, FileUpload, DropDownList, ListBox etc…i.e. not all Server controls can be validated using Validation Controls.


SandeepSoni

Mr Sandeep Soni, CEO & Founder of Deccansoft Software Services. He has over 21years of Experience in Teaching and Development using Microsoft Technologies. Since 1997, of the total 100000+ students, Deccansoft has trained, he has personally trained over 60,000+ students and we are proud of him because almost every student he had trained is very happy with the quality and many are well placed in various I.T Firms. This will reflect in testimonials on our website.

Please follow and like us:
0

Leave a Reply

Your email address will not be published. Required fields are marked *