All validation controls other than RequiredFieldValidator consider a blank field to be valid. In fact, if one field has a value and another field is blank, the CompareValidator will consider the values valid. To avoid this problem, add RequiredFieldValidator.
In order to use standard validation controls, you need to enable the pre 4.5 validation mode by inserting the following setting into web.config:
<appSettings> <add key="ValidationSettings:UnobtrusiveValidationMode" value="None" /> </appSettings>
Examples of standard validation controls:
<!-- Ensure that there is a value entered in a textbox --> 1. <asp:TextBox ID="TextBox1" runat="server" /> <asp:RequiredFieldValidator id="Validator1" ControlToValidate="TextBox1" Display="Dynamic" ErrorMessage="Required" ForeColor="Red" runat="server" /> <br /><br /> <!-- Ensure that an item is selected from a drop-down list --> 2. <asp:DropDownList ID="DropDownList1" Width="100" runat="server"> <asp:ListItem Value="0" Text="[Select]" /> <asp:ListItem Value="1" Text="AAA" /> <asp:ListItem Value="2" Text="BBB" /> <asp:ListItem Value="3" Text="CCC" /> </asp:DropDownList> <asp:RequiredFieldValidator id="Validator2" ControlToValidate="DropDownList1" Display="Dynamic" InitialValue="0" ErrorMessage="Required" ForeColor="Red" runat="server" /> <br /><br /> <!-- Ensure that the entered number is greater than zero --> 3. <asp:TextBox ID="TextBox2" runat="server" /> <asp:CompareValidator id="Validator3" ControlToValidate="TextBox2" Display="Dynamic" Type="Integer" Operator="GreaterThan" ValueToCompare="0" ErrorMessage="Must be greater than zero" ForeColor="Red" runat="server" /> <br /><br /> <!-- Ensure that the entered value is a number --> <!-- The Type attribute is a ValidationDataType enum: Currency, Date, Double, Integer, String --> 4. <asp:TextBox ID="TextBox3" runat="server" /> <asp:CompareValidator id="Validator4" ControlToValidate="TextBox3" Display="Dynamic" Type="Integer" Operator="DataTypeCheck" ErrorMessage="Must be a number" ForeColor="Red" runat="server" /> <br /><br /> <!-- Ensure that two fields have identical values --> 5. <asp:TextBox id="TextBox4" runat="server" /> <asp:RequiredFieldValidator id="Validator5" ControlToValidate="TextBox4" Display="Dynamic" ErrorMessage="Required" ForeColor="Red" runat="server" /><br /> 6. <asp:TextBox id="TextBox5" runat="server" /> <asp:RequiredFieldValidator id="Validator6" ControlToValidate="TextBox5" Display="Dynamic" ErrorMessage="Required" ForeColor="Red" runat="server" /><br /> <asp:CompareValidator id="CompareValidator1" ControlToValidate="TextBox4" ControlToCompare="TextBox5" Type="String" Operator="Equal" ErrorMessage ="Values do not match" ForeColor="Red" runat="server" /> <br /><br /> <!-- Ensure that the entered number is between 1 and 999 --> 7. <asp:TextBox id="TextBox6" MaxLength="4" runat="server" /> <asp:RangeValidator id="Validator7" ControlToValidate="TextBox6" Display="Dynamic" Type="Integer" MinimumValue="1" MaximumValue="999" ErrorMessage="Must be between 1 and 999" ForeColor="Red" runat="server" /> <br /><br /> <!-- Ensure that the entered value is a valid email address --> 8. <asp:TextBox ID="txtEmail" MaxLength="50" runat="server" /> <asp:RegularExpressionValidator ID="Validator8" ControlToValidate="txtEmail" Display="Dynamic" ValidationExpression="\w[-._\w]*\w@\w[-._\w]*\w\.\w{2,3}" ErrorMessage="Email formatted incorrectly" ForeColor="Red" runat="server" /> <br /><br /> <!-- Ensure that the entered value is a valid Canadian postal code --> 9. <asp:TextBox ID="txtPostalCode" MaxLength="10" runat="server" /> <asp:RegularExpressionValidator ID="Validator9" ControlToValidate="txtPostalCode" Display="Dynamic" ValidationExpression="[a-zA-Z][0-9][a-zA-Z](\s|\-|)[0-9][a-zA-Z][0-9]" ErrorMessage="Postal code formatted incorrectly" ForeColor="Red" runat="server" /> <br /><br /> <asp:Button ID="btnSubmit" Text="Submit" runat="server" />
This is an example of entering invalid values:
This is an example of entering valid values:
All ASP.NET validation controls can be invoked on the client-side by setting the EnableClientScript attribute to True, for example:
<!-- Enable client-side validation --> <asp:TextBox ID="txtZipCode" MaxLength="10" runat="server" /> <asp:RegularExpressionValidator id="Validator1" ControlToValidate="txtZipCode" Display="Dynamic" ValidationExpression="^\d{5}$" ErrorMessage="Zip code formatted incorrectly" EnableClientScript="true" runat="server" />
It is also possible to disable all validators on a web page:
foreach(BaseValidator val in Page.Validators) val.Enabled = false;
An example of using the CustomValidator control. It ensures that the entered number is even:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebTest.Default" %> <html> <head runat="server"> <title>Test</title> <script lang="javascript" type="text/javascript"> function CheckValueClient(source, arguments) { if (arguments.Value % 2 == 0) arguments.IsValid = true; else { alert("Invalid number"); arguments.IsValid = false; } } </script> </head> <body> <form id="form1" runat="server"> <asp:TextBox ID="txtNumber" MaxLength="10" runat="server" /> <asp:CustomValidator id="Validator1" ControlToValidate="txtNumber" Display="Dynamic" ClientValidationFunction="CheckValueClient" OnServerValidate="CheckValueServer" ErrorMessage="The number must be even" ForeColor="Red" runat="server" /> <asp:Button ID="btnSubmit" Text="Submit" runat="server" /> </form> </body> </html>
using System; using System.Web.UI.WebControls; namespace WebTest { public partial class Default : System.Web.UI.Page { // Server-side validator public void CheckValueServer(object source, ServerValidateEventArgs e) { int num; if (Int32.TryParse(e.Value, out num)) e.IsValid = (num % 2 == 0); else e.IsValid = false; } } }
The following code creates two text boxes each with RequiredFieldValidator as well as three buttons:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebTest.Default" %> <html> <head runat="server"> <title>Test</title> <style> * { font-family: Arial; font-size: 10pt; } </style> <script lang="javascript" type="text/javascript"> function EnableValidator(valId, enable) { for (i = 0; i < Page_Validators.length; i++) { val = Page_Validators[i]; if (val.id == valId) { val.enabled = enable; val.style.display = (enable ? "inline" : "none"); } } } </script> </head> <body> <form id="form1" runat="server"> <asp:TextBox ID="TextBox1" runat="server" /> <asp:RequiredFieldValidator id="Validator1" ControlToValidate="TextBox1" Display="Dynamic" ErrorMessage="Required" ForeColor="Red" runat="server" /> <br /><br /> <asp:TextBox ID="TextBox2" runat="server" /> <asp:RequiredFieldValidator id="Validator2" ControlToValidate="TextBox2" Display="Dynamic" ErrorMessage="Required" ForeColor="Red" runat="server" /> <br /><br /> <asp:Button ID="btnSubmit" Text="Submit" runat="server" /> <input type="button" onclick="EnableValidator('Validator2', false)" value="Disable" /> <input type="button" onclick="EnableValidator('Validator2', true)" value="Enable" /> </form> </body> </html>
Sometimes you may want to invoke client-side validation on demand rather than automatically. In order to do that set the CausesValidation property of the Submit button to False and invoke the following JavaScript function ValidateForm(). It allows you to validate the form on demand and to perform any additional actions on the client-side:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebTest.Default" %> <html> <head runat="server"> <title>Test</title> <style> * { font-family: Arial; font-size: 10pt; } </style> <script lang="javascript" type="text/javascript"> function ValidateForm() { var isValid = true; if (typeof (Page_ClientValidate) == 'function') { Page_ClientValidate(); // validate the form on demand isValid = Page_IsValid; } if (isValid) { // perform any additional actions on the client-side // only if the form is valid } return isValid; } </script> </head> <body> <form id="form1" runat="server"> <asp:TextBox ID="TextBox1" runat="server" /> <asp:RequiredFieldValidator id="Validator1" ControlToValidate="TextBox1" Display="Dynamic" ErrorMessage="Required" ForeColor="Red" runat="server" /> <br /><br /> <asp:TextBox ID="TextBox2" runat="server" /> <asp:RequiredFieldValidator id="Validator2" ControlToValidate="TextBox2" Display="Dynamic" ErrorMessage="Required" ForeColor="Red" runat="server" /> <br /><br /> <asp:Button id="btnSubmit" Text="Submit" OnClick="btnSubmit_Click" OnClientClick="javascript: return ValidateForm();" CausesValidation="false" runat="server" /> </form> </body> </html>