Wednesday, 27 July 2011

User Input Validation - Client & Server - in C#.NET


This tutorial shows how you can validate the input of users using ASP.NET and C#

This tutorial shows how the ASP.NET tools make it easy for you to validate user input, both client-side and server-side.

First we add the form elements from the Toolbox, including the RequiredFieldValidator, RegularExpressionValidator and the ValidationSummary.
Note the CustomValidator control, which allows us to create a custom rule for validation. This particular one checks to see if a date is in the correct format:

<form id="form1" runat="server">
<div>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate="textEmail" Display="Dynamic" ErrorMessage="Email Address is Required" ValidationGroup="AllValidators">*</asp:RequiredFieldValidator>
Email:
<asp:TextBox ID="textEmail" runat="server"></asp:TextBox> 
<asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server" ControlToValidate="textEmail" Display="Dynamic" ErrorMessage="Email Address must be in the format abc@xyz.abc" ValidationExpression="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*" ValidationGroup="AllValidators">Invalid Format</asp:RegularExpressionValidator><br />

<asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" ControlToValidate="textNumberInParty" ErrorMessage="Number in Party is Required" ValidationGroup="AllValidators">*</asp:RequiredFieldValidator>
Number in Party:
<asp:TextBox ID="textNumberInParty" runat="server" Width="45px"></asp:TextBox> 
<asp:RangeValidator ID="RangeValidator1" runat="server" ControlToValidate="textNumberInParty" Display="Dynamic" ErrorMessage="Please enter 1-20 for the number of people in your party" MaximumValue="20" MinimumValue="1" Type="Integer" ValidationGroup="AllValidators">Enter a number between 1 and 20</asp:RangeValidator><br />

<asp:RequiredFieldValidator ID="RequiredFieldValidator3" runat="server" ControlToValidate="textPreferredDate" Display="Dynamic" ErrorMessage="Date is Required" ValidationGroup="AllValidators">*</asp:RequiredFieldValidator>
Preferred Date:
<asp:TextBox ID="textPreferredDate" runat="server"></asp:TextBox>
<asp:CustomValidator ID="CustomValidator1" runat="server" ControlToValidate="textPreferredDate" Display="Dynamic" ErrorMessage="Format: m/d/yyyy" OnServerValidate="CustomValidator1_ServerValidate" ValidationGroup="AllValidators" ClientValidationFunction="validateDate">Invalid format (m/d/yyyy)</asp:CustomValidator><br />

<asp:RequiredFieldValidator ID="validatorRequiredPhoneNumber" runat="server" ControlToValidate="textPhoneNumber" Display="Dynamic" ErrorMessage="You must provide a phone number">*</asp:RequiredFieldValidator>
<asp:CheckBox ID="checkPhoneConfirmation" runat="server" AutoPostBack="True" OnCheckedChanged="checkPhoneConfirmation_CheckedChanged" Text="Confirm Reservation by Phone" /><br />
Tel. No.
<asp:TextBox ID="textPhoneNumber" runat="server" Enabled="False"></asp:TextBox> 
<asp:RegularExpressionValidator ID="validatorRegExPhoneNumber" runat="server" ControlToValidate="textPhoneNumber" Display="Dynamic" ErrorMessage="Phone number format is invalid" ValidationExpression="((\(\d{3}\) ?)|(\d{3}-))?\d{3}-\d{4}">Invalid Format</asp:RegularExpressionValidator><br />
<asp:Button ID="buttonSubmit" runat="server" OnClick="buttonSubmit_Click" Text="Submit" ValidationGroup="AllValidators" /><br />
<asp:Label ID="labelResponse" runat="server"></asp:Label><br />
<asp:ValidationSummary ID="ValidationSummary1" runat="server" ValidationGroup="AllValidators" />
</div>
</form>

We chose Server Intellect for its dedicated servers, for our web hosting. They have managed to handle virtually everything for us, from start to finish. And their customer service is stellar.

In the code-behind file we have the following:

protected void Page_Load(object sender, EventArgs e)
{
labelResponse.Text = "";
}
protected void buttonSubmit_Click(object sender, EventArgs e)
{
if (Page.IsValid)
{
labelResponse.Text = "Your request has been processed. Thank you.";
}
else
{
labelResponse.Text = "Date is not valid.";
}
}
protected void CustomValidator1_ServerValidate(object source, ServerValidateEventArgs args)
{
try
{
DateTime.ParseExact(args.Value, "d", null);
args.IsValid = true;
}
catch
{
args.IsValid = false;
}
} protected void checkPhoneConfirmation_CheckedChanged(object sender, EventArgs e)
{
if(checkPhoneConfirmation.Checked)
{
textPhoneNumber.Enabled = true;
validatorRequiredPhoneNumber.ValidationGroup = "AllValidators";
validatorRegExPhoneNumber.ValidationGroup = "AllValidators";
}
else
{
textPhoneNumber.Enabled = false;
validatorRequiredPhoneNumber.ValidationGroup = "";
validatorRegExPhoneNumber.ValidationGroup = "";
}
}

We moved our web sites to Server Intellect and have found them to be incredibly professional. Their setup is very easy and we were up and running in no time.

For client-side validation of the date field, we can use a bit of JavaScript:
Note: For this to work, the 'EnableClientScript' Property of the CustomValidator has to be set to True.

<script language="javascript">
function validateDate(oSrc, args)
{
var iDay, iMonth, iYear;
var arrValues;
arrValues = args.Value.split("/");
iMonth = arrValues[0];
iDay = arrValues[1];
iYear = arrValues[2];

var testDate = new Date(iYear, iMonth - 1, iDay);
if ((testDate.getDate() != iDay) ||
(testDate.getMonth() != iMonth - 1) ||
(testDate.getFullYear() != iYear))
{
args.IsValid = false;
return;
}

return true;
} </script>

Looking for the VB.NET 2005 Version? Click Here!

Looking for more ASP.NET Tutorials? Click Here!

No comments:

Post a Comment