✅ ASP.NET – Validators – Beginner’s Guide to Validating User Input in Web Forms
🧲 Introduction – What Are ASP.NET Validators?
ASP.NET Validators are server-side controls that ensure the data entered by users is valid, complete, and matches specific rules before it’s processed. They are essential for protecting your application from bad input, empty fields, wrong formats, and invalid data types.
Instead of writing manual validation logic, ASP.NET Web Forms provides ready-made validation controls like:
RequiredFieldValidator
RangeValidator
RegularExpressionValidator
CompareValidator
CustomValidator
ValidationSummary
🎯 In this guide, you’ll learn:
- How to use each ASP.NET validation control
- How to attach them to inputs like
TextBox
orDropDownList
- How validation works automatically on postback
- Complete code with step-by-step output and beginner explanations
📂 ASP.NET Web Forms File Structure
📁 File Name | 📘 Description |
---|---|
ValidatorsDemo.aspx | Markup file with input fields and validators |
ValidatorsDemo.aspx.cs | Optional code-behind file for custom logic (if needed) |
📄 Step 1: Markup File – ValidatorsDemo.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="ValidatorsDemo.aspx.cs" Inherits="ValidatorsDemo.ValidatorsDemo" %>
<html>
<body>
<form id="form1" runat="server">
<h3>✅ ASP.NET Validators Demo</h3>
<!-- Name (Required) -->
<asp:Label ID="lblName" runat="server" Text="Enter Name:" /><br />
<asp:TextBox ID="txtName" runat="server" /><br />
<asp:RequiredFieldValidator ID="rfvName" runat="server"
ControlToValidate="txtName"
ErrorMessage="Name is required"
ForeColor="Red" Display="Dynamic" /><br /><br />
<!-- Age (Range 18-60) -->
<asp:Label ID="lblAge" runat="server" Text="Enter Age:" /><br />
<asp:TextBox ID="txtAge" runat="server" /><br />
<asp:RangeValidator ID="rvAge" runat="server"
ControlToValidate="txtAge"
MinimumValue="18" MaximumValue="60"
Type="Integer"
ErrorMessage="Age must be between 18 and 60"
ForeColor="Red" Display="Dynamic" /><br /><br />
<!-- Email (Regex check) -->
<asp:Label ID="lblEmail" runat="server" Text="Enter Email:" /><br />
<asp:TextBox ID="txtEmail" runat="server" /><br />
<asp:RegularExpressionValidator ID="revEmail" runat="server"
ControlToValidate="txtEmail"
ErrorMessage="Invalid email format"
ValidationExpression="\w+@\w+\.\w+"
ForeColor="Red" Display="Dynamic" /><br /><br />
<!-- Password and Confirm Password -->
<asp:Label ID="lblPassword" runat="server" Text="Password:" /><br />
<asp:TextBox ID="txtPassword" runat="server" TextMode="Password" /><br /><br />
<asp:Label ID="lblConfirm" runat="server" Text="Confirm Password:" /><br />
<asp:TextBox ID="txtConfirm" runat="server" TextMode="Password" /><br />
<asp:CompareValidator ID="cvPassword" runat="server"
ControlToCompare="txtPassword"
ControlToValidate="txtConfirm"
ErrorMessage="Passwords do not match"
ForeColor="Red" Display="Dynamic" /><br /><br />
<!-- Submit -->
<asp:Button ID="btnSubmit" runat="server" Text="Submit" /><br /><br />
<!-- Summary of Errors -->
<asp:ValidationSummary ID="valSummary" runat="server"
HeaderText="Please fix the following:"
ForeColor="DarkRed" />
</form>
</body>
</html>
🔍 Explanation of Each Validator
Validator | Purpose |
---|---|
RequiredFieldValidator | Ensures a field is not left empty |
RangeValidator | Checks if a value falls within a defined numeric or date range |
RegularExpressionValidator | Validates format (email, phone, etc.) using regex |
CompareValidator | Compares two values (e.g., password match) |
ValidationSummary | Displays all errors in a single place |
⚙️ Step 2: Code-Behind File – ValidatorsDemo.aspx.cs
No C# code is required unless you want to add custom validation logic. You can, however, add a confirmation message like this:
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack && Page.IsValid)
{
Response.Write("<b>Form submitted successfully!</b>");
}
}
🔍 C# Explanation
Code | 💡 What It Does |
---|---|
IsPostBack | Checks if the form was submitted |
Page.IsValid | Returns true only if all validators pass |
Response.Write(...) | Shows a success message without redirecting |
🖥️ Output Preview in Browser
▶️ When Form is Empty and Submitted:
❌ Name is required
❌ Age must be between 18 and 60
❌ Invalid email format
❌ Passwords do not match
▶️ When Correct Values Entered:
✔️ Form submitted successfully!
📌 Summary – Recap & Takeaways
ASP.NET Validator controls allow you to validate user inputs with no extra logic in your backend.
🔍 Key Learnings:
- Use
RequiredFieldValidator
to prevent blank fields - Use
RangeValidator
to set valid age or numeric ranges - Use
RegularExpressionValidator
for email or pattern-based validation - Use
CompareValidator
for password confirmation ValidationSummary
shows a list of all errors
✅ These validators run automatically on the server and are also compatible with client-side validation in modern browsers.
❓ Frequently Asked Questions (FAQs)
❓ Do validators run on the client or server?
✅ Both. ASP.NET generates JavaScript for client-side validation but also performs server-side validation for security.
❓ Can I customize error messages?
✅ Yes. Use the ErrorMessage
property in each validator to write user-friendly messages.
❓ What if I want to validate based on a dropdown or checkbox?
✅ You can use RequiredFieldValidator
with InitialValue
or create a CustomValidator
for more advanced logic.
❓ Can I disable a specific validator programmatically?
✅ Yes:
rfvName.Enabled = false;
Share Now :