To enable client validation below scripts are required to added to the view.
<script src="@Url.Content("~/Scripts/jquery-1.6.1.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.js")" type="text/javascript"></script>
When we create an internet application in MVC3/MVC4 by default below settings are enabled in web.config.
<appSettings>
<add key="ClientValidationEnabled" value="true"/>
<add key="UnobtrusiveJavaScriptEnabled" value="true"/>
</appSettings>
To disable client side validation for the entire application we can set above settings to false.
<appSettings>
<add key="ClientValidationEnabled" value="false"/>
<add key="UnobtrusiveJavaScriptEnabled" value="false"/>
</appSettings>
Showing posts with label Validation. Show all posts
Showing posts with label Validation. Show all posts
Wednesday, June 26, 2013
Thursday, April 4, 2013
E-mail Validation in HTML5


E-mail addresses are commonly used on web sites for variety of reasons ranging from user registrations to
contact forms. You can accept e-mail addresses using the email input type.
<span>Enter your email address :</span>
<br />
<input id="email" type="email" />
<br />
<input type="submit" value="Submit"/>
As you can see, the type attribute is set to email. If you try to enter an invalid e-mail address, the browser displays an error message.
Notice that the error message is displayed only if the text box contains a value. If the text box is left empty, no validation is performed. This behavior is similar to ASP.NET validation controls.
Monday, February 11, 2013
Simple Validation Form In Jquery

Preview On Focus:

Preview On Button Click:

Below is our HTML form with one text box and the validation messages.

Preview On Button Click:

Below is our HTML form with one text box and the validation messages.
<form id="form1" runat="server">Add the form style.
<fieldset class="formContainer">
<h3>Simple Validation Form.</h3>
<div class="rowContainer">
<label for="txtFirstname">Choose a username</label>
<input id="txtFirstname" type="text"/>
<div class="tooltipContainer info">Minimum 4 characters, maximum 15 characters.</div>
<div class="tooltipContainer error">Username must be between 4 and 15 characters.</div>
</div>
<input type="button" id="btnSubmit" value="Sign in" onclick="validateForm()"/>
</fieldset>
</form>
<style type="text/css">
body
{
font-family:Arial, Sans-Serif;
font-size:83%;
}
.formContainer
{
background-color:#F5EFC9;
border:none;
padding:30px;
}
.formContainer h3
{
margin:0px;
padding:0px 0px 10px 0px;
font-size:135%;
}
.rowContainer
{
width:100%;
overflow:hidden;
padding-bottom:5px;
height:34px;
}
.rowContainer label
{
width:140px;
float:left;
color: #758656;
font-weight:bold;
}
.rowContainer input[type="text"]
{
width:200px;
}
.tooltipContainer
{
height:16px;
font-size:11px;
color: #666666;
display:none;
float:none;
background-repeat:no-repeat;
background-position:left center;
padding:0px 20px;
}
.info
{
background-image:url('info.gif');
}
.error
{
background-image:url('error.gif');
}
</style>
Add the Jquery script to validate the form.
<script type="text/javascript">
$(document).ready(function () {
$(".formContainer input[type=text]").focus(function () {
$(this).parent().find(".error").css("display", "none");
$(this).parent().find(".info").css("display", "block");
}).blur(function () {
$(this).parent().find(".info").css("display", "none");
});
});
function validateForm() {
$(".formContainer input[type=text]").each(function () {
var text = $(this).attr("value");
if (text == "") {
$(this).parent().find(".error").css("display", "block");
}
if (text.length < 5) {
$(this).parent().find(".error").css("display", "block");
}
});
}
function clearForm() {
$(".formContainer input[type=text]").each(function () {
$(this).parent().find(".error").css("display", "none");
});
}
</script>
Wednesday, January 16, 2013
Server-Side and Client-Side Validation in ASP.NET

Server-Side Validation
You can use the validator controls to verify a page automatically when the user submits it or manually in your code. The first approach is the most common. When using automatic validation, the user receives a normal page and begins to fill in the input controls. When finished, the user clicks a button to submit the page. Every button has a CausesValidation property, which can be set to true or false. What happens when the user clicks the button depends on the value of the CausesValidation property:
• If CausesValidation is false, ASP.NET will ignore the validation controls, the page will be posted back, and your event-handling code will run normally.
• If CausesValidation is true (the default), ASP.NET will automatically validate the page when the user clicks the button. It does this by performing the validation for each control on the page. If any control fails to validate, ASP.NET will return the page with some error information, depending on your settings. Your click event-handling code may or may not be executed—meaning you’ll have to specifically check in the event handler whether the page is valid.
Based on this description, you’ll realize that validation happens automatically when certain buttons are clicked. It doesn’t happen when the page is posted back because of a change event (such as choosing a new value in an AutoPostBack list) or if the user clicks a button that has CausesValidation set to false. However, you can still validate one or more controls manually and then make a decision in your code based on the results.
Client-Side Validation
In most modern browsers (including Internet Explorer 5 or later and any version of Firefox), ASP.NET automatically adds JavaScript code for client-side validation. In this case, when the user clicks a CausesValidation button, the same error messages will appear without the page needing to be submitted and returned from the server. This increases the responsiveness of your web page. However, even if the page validates successfully on the client side, ASP.NET still revalidates it when it’s received at the server. This is because it’s easy for an experienced user to circumvent client-side validation. For example, a malicious user might delete the block of JavaScript validation code and continue working with the page. By performing the validation at both ends, ASP.NET makes sure your application can be as responsive as possible while also remaining secure.
Thursday, January 10, 2013
Allow spaces when validating email using regular expressions

I have used below regular expression to validate the email address in asp.net RegularExpressionValidator control.
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server"
ControlToValidate="TextBox1"
ValidationExpression="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*">*</asp:RegularExpressionValidator>
It's validating the email address correctly but when a user enter a space at the beginning or at the end of the email address the validator fired as its a invalid email address.
Below regular expression will ignore the spaces at the end and the beginning of the email address.
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server"
ControlToValidate="TextBox1"
ValidationExpression="\s*\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*\s*">*</asp:RegularExpressionValidator>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server"
ControlToValidate="TextBox1"
ValidationExpression="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*">*</asp:RegularExpressionValidator>
It's validating the email address correctly but when a user enter a space at the beginning or at the end of the email address the validator fired as its a invalid email address.
Below regular expression will ignore the spaces at the end and the beginning of the email address.
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server"
ControlToValidate="TextBox1"
ValidationExpression="\s*\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*\s*">*</asp:RegularExpressionValidator>
Thursday, January 3, 2013
How to use CustomValidator with Server Side Validation Method

Below is the custom validator.
<asp:CustomValidator id="CustomValidator1" runat="server" OnServerValidate="RevisionValidate" ControlToValidate="TextBoxRevisionOrder" ErrorMessage="Invalid RevOrder Format"> </asp:CustomValidator>
OnServerValidate - Server side method name.
ControlToValidate - Text box id to validate.
protected void RevisionValidate(object source, ServerValidateEventArgs args)
<asp:CustomValidator id="CustomValidator1" runat="server" OnServerValidate="RevisionValidate" ControlToValidate="TextBoxRevisionOrder" ErrorMessage="Invalid RevOrder Format"> </asp:CustomValidator>
OnServerValidate - Server side method name.
ControlToValidate - Text box id to validate.
protected void RevisionValidate(object source, ServerValidateEventArgs args)
{
//Validation Code goes here
}
On a button click event i need to fire the validation.
Inside the button click event first you need to add the below code.
if(Page.IsValid) {
}
Any other code that you need to execute on the button click event, add inside the above "if" condition.
}
On a button click event i need to fire the validation.
Inside the button click event first you need to add the below code.
if(Page.IsValid) {
}
Any other code that you need to execute on the button click event, add inside the above "if" condition.
Tuesday, December 25, 2012
ASP.NET Validation Controls : Show Validation Message only on Validation Summary


One of my previous posts I have described how to use Validation summary on a web page. In case you need only to show the validation summary and hide any other validation text for individual controls, you can do the following.
Set the Display property to "None".
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server"
ControlToValidate="txtName" ErrorMessage="Name Required"
ForeColor="#CC0000" Display="None" Text="*"></asp:RequiredFieldValidator>
Monday, December 24, 2012
ASP.NET Validation Controls: Validation Summary

You can use a validation summary control in ASP.NET when you want to show a detail description of the error messages. The error message is assign to the "ErrorMessage" property of each validation control and "Text" property is assign to "*".
Following would be your HTML code.
<asp:ValidationSummary ID="ValidationSummary1" runat="server"
ForeColor="#CC0000" />
<table>
<tr>
<td>
Name:</td>
<td>
<asp:TextBox ID="txtName" runat="server" Width="153px"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server"
ControlToValidate="txtName" ErrorMessage="Name Required" ForeColor="#CC0000">*</asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td>
Address:</td>
<td>
<asp:TextBox ID="txtAddress" runat="server" Width="155px"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server"
ControlToValidate="txtAddress" ErrorMessage="Address Required"
ForeColor="#CC0000">*</asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td>
Profession:</td>
<td>
<asp:TextBox ID="txtProf" runat="server" Width="153px"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator3" runat="server"
ControlToValidate="txtProf" ErrorMessage="Profession Required"
ForeColor="#CC0000">*</asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td>
Desscription:</td>
<td>
<asp:TextBox ID="txtdescription" runat="server" Width="152px"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator4" runat="server"
ControlToValidate="txtdescription" ErrorMessage="Description Required"
ForeColor="#CC0000">*</asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td>
</td>
<td>
<asp:Button ID="btnSubmit" runat="server" Text="Submit" />
</td>
</tr>
</table>
Sunday, December 23, 2012
ASP.NET Validation Controls: Range Validator

Range validator control in ASP.NET makes it possible to validate a specified range.
This range could be
<asp:RangeValidator ID="RangeValidator1" runat="server" ControlToValidate="TextBox1" MaximumValue="d" MinimumValue="a" Text="*" Type="String"></asp:RangeValidator>
<asp:Button ID="Button2" runat="server" Text="Submit" />
In the above example the text starting from a to d will only be allowed. You can change the below properties.
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:RangeValidator ID="RangeValidator1" runat="server" ControlToValidate="TextBox1" MaximumValue="100" MinimumValue="0" Text="*" Type="Integer"></asp:RangeValidator>
<asp:Button ID="Button2" runat="server" Text="Submit" />
Note: Empty text will not be validated by the control. You'll need to add a Required Field validator to validate the empty text.
This range could be
- String
- Integer
- Double
- Date
- Currency
<asp:RangeValidator ID="RangeValidator1" runat="server" ControlToValidate="TextBox1" MaximumValue="d" MinimumValue="a" Text="*" Type="String"></asp:RangeValidator>
<asp:Button ID="Button2" runat="server" Text="Submit" />
In the above example the text starting from a to d will only be allowed. You can change the below properties.
- ControlToValidate
- MaximumValue
- MinimumValue
- Type
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:RangeValidator ID="RangeValidator1" runat="server" ControlToValidate="TextBox1" MaximumValue="100" MinimumValue="0" Text="*" Type="Integer"></asp:RangeValidator>
<asp:Button ID="Button2" runat="server" Text="Submit" />
Note: Empty text will not be validated by the control. You'll need to add a Required Field validator to validate the empty text.
Friday, December 14, 2012
ASP.NET Validation Controls: Compare Validator

In a user registration form submitting the password is a common application. In such a case we need to ensure that the user entered his/her expected password. To ensure we can let user to enter the password two times and compare the password in the two text boxes. CompareValidator can be used in this scenario.

<table>
<tr>
<td>Password: </td>
<td>
<asp:TextBox ID="TextBox1" runat="server" TextMode="Password"></asp:TextBox>
</td>
</tr>
<tr>
<td>Retype Password:</td>
<td>
<asp:TextBox ID="TextBox2" runat="server" TextMode="Password"></asp:TextBox>
<asp:CompareValidator ID="CompareValidator1" runat="server" ControlToCompare="TextBox1"
ControlToValidate="TextBox2" ForeColor="#CC0000">Password mismatch</asp:CompareValidator>
</td>
</tr>
<tr>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td><asp:Button ID="Button3" runat="server" Text="Submit" /> </td>
</tr>
</table>

<table>
<tr>
<td>Password: </td>
<td>
<asp:TextBox ID="TextBox1" runat="server" TextMode="Password"></asp:TextBox>
</td>
</tr>
<tr>
<td>Retype Password:</td>
<td>
<asp:TextBox ID="TextBox2" runat="server" TextMode="Password"></asp:TextBox>
<asp:CompareValidator ID="CompareValidator1" runat="server" ControlToCompare="TextBox1"
ControlToValidate="TextBox2" ForeColor="#CC0000">Password mismatch</asp:CompareValidator>
</td>
</tr>
<tr>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td><asp:Button ID="Button3" runat="server" Text="Submit" /> </td>
</tr>
</table>
Thursday, December 13, 2012
ASP.NET Validation Controls: Validating DropDown List Selection

Some times when user submitting the web form we need to make sure that the dropdown list is selected other than it's default values.

In the example "Select Below" is the default text and the values is "0" in the dropdown list. Validation fires if the selected value is "0" that means when the selected text is "Select below".
Let's load some values to the dropdown list.
private void LoadDropDown()
{
DropDownList2.Items.Insert(0,new ListItem("Select Below","0"));
DropDownList2.Items.Insert(1,new ListItem("Item1","1"));
DropDownList2.Items.Insert(2, new ListItem("Item2", "2"));
DropDownList2.Items.Insert(3, new ListItem("Item3", "3"));
DropDownList2.Items.Insert(4, new ListItem("Item4", "4"));
}
Below is the HTML code.
<asp:DropDownList ID="DropDownList2" runat="server">
</asp:DropDownList>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server"
ControlToValidate="DropDownList2" ForeColor="#CC0000" InitialValue="0">*</asp:RequiredFieldValidator>
<br />
<table>
<tr style="font-weight: bold">
<td>
</td>
<td>
<asp:Button ID="Button2" runat="server" Text="Submit" />
</td>
</tr>
</table>
We have used the RequiredFieldValidator Control. Note the Initial values property, it's set to "0".

In the example "Select Below" is the default text and the values is "0" in the dropdown list. Validation fires if the selected value is "0" that means when the selected text is "Select below".
Let's load some values to the dropdown list.
private void LoadDropDown()
{
DropDownList2.Items.Insert(0,new ListItem("Select Below","0"));
DropDownList2.Items.Insert(1,new ListItem("Item1","1"));
DropDownList2.Items.Insert(2, new ListItem("Item2", "2"));
DropDownList2.Items.Insert(3, new ListItem("Item3", "3"));
DropDownList2.Items.Insert(4, new ListItem("Item4", "4"));
}
Below is the HTML code.
<asp:DropDownList ID="DropDownList2" runat="server">
</asp:DropDownList>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server"
ControlToValidate="DropDownList2" ForeColor="#CC0000" InitialValue="0">*</asp:RequiredFieldValidator>
<br />
<table>
<tr style="font-weight: bold">
<td>
</td>
<td>
<asp:Button ID="Button2" runat="server" Text="Submit" />
</td>
</tr>
</table>
We have used the RequiredFieldValidator Control. Note the Initial values property, it's set to "0".
Wednesday, December 5, 2012
Simple JavaScript Validation in ASP.NET Web form

Design the web form as below.
<form id="form1" runat="server">
<div>
<table class="style1">
<tr>
<td>Name: </td>
<td><asp:TextBox ID="txtName" runat="server" /></td>
</tr>
<tr>
<td>Email: </td>
<td><asp:TextBox ID="txtEmail" runat="server"/></td>
</tr>
<tr>
<td>URL: </td>
<td><asp:TextBox ID="txtWebURL" runat="server" /></td>
</tr>
<tr>
<td>ZIP: </td>
<td><asp:TextBox ID="txtZIP" runat="server" /> </td>
</tr>
<tr>
<td> </td>
<td><asp:Button ID="btnSubmit" OnClientClick=" return validate()" runat="server"
Text="Submit" onclick="btnSubmit_Click" /></td>
</tr>
</table>
</div>
</form>
Now add the below JavaScript code in the header section of the page.
<script language="javascript" type="text/javascript">
On the page Load event add the below code.
protected void Page_Load(object sender, EventArgs e)
{
btnSubmit.Attributes.Add("onclick", "return validate()");
}
<form id="form1" runat="server">
<div>
<table class="style1">
<tr>
<td>Name: </td>
<td><asp:TextBox ID="txtName" runat="server" /></td>
</tr>
<tr>
<td>Email: </td>
<td><asp:TextBox ID="txtEmail" runat="server"/></td>
</tr>
<tr>
<td>URL: </td>
<td><asp:TextBox ID="txtWebURL" runat="server" /></td>
</tr>
<tr>
<td>ZIP: </td>
<td><asp:TextBox ID="txtZIP" runat="server" /> </td>
</tr>
<tr>
<td> </td>
<td><asp:Button ID="btnSubmit" OnClientClick=" return validate()" runat="server"
Text="Submit" onclick="btnSubmit_Click" /></td>
</tr>
</table>
</div>
</form>
Now add the below JavaScript code in the header section of the page.
<script language="javascript" type="text/javascript">
function validate()
{
if (document.getElementById("<%=txtName.ClientID%>").value=="")
{
alert("Name Feild can not be blank");
document.getElementById("<%=txtName.ClientID%>").focus();
return false;
}
if(document.getElementById("<%=txtEmail.ClientID %>").value=="")
{
alert("Email id can not be blank");
document.getElementById("<%=txtEmail.ClientID %>").focus();
return false;
}
var emailPat = /^(\".*\"|[A-Za-z]\w*)@(\[\d{1,3}(\.\d{1,3}){3}]|[A-Za-z]\w*(\.[A-Za-z]\w*)+)$/;
var emailid=document.getElementById("<%=txtEmail.ClientID %>").value;
var matchArray = emailid.match(emailPat);
if (matchArray == null)
{
alert("Your email address seems incorrect. Please try again.");
document.getElementById("<%=txtEmail.ClientID %>").focus();
return false;
}
if(document.getElementById("<%=txtWebURL.ClientID %>").value=="")
{
alert("Web URL can not be blank");
document.getElementById("<%=txtWebURL.ClientID %>").value="http://"
document.getElementById("<%=txtWebURL.ClientID %>").focus();
return false;
}
var Url="^[A-Za-z]+://[A-Za-z0-9-_]+\\.[A-Za-z0-9-_%&\?\/.=]+$"
var tempURL=document.getElementById("<%=txtWebURL.ClientID%>").value;
var matchURL=tempURL.match(Url);
if(matchURL==null)
{
alert("Web URL does not look valid");
document.getElementById("<%=txtWebURL.ClientID %>").focus();
return false;
}
if (document.getElementById("<%=txtZIP.ClientID%>").value=="")
{
alert("Zip Code is not valid");
document.getElementById("<%=txtZIP.ClientID%>").focus();
return false;
}
var digits="0123456789";
var temp;
for (var i=0;i<document.getElementById("<%=txtZIP.ClientID %>").value.length;i++)
{
temp=document.getElementById("<%=txtZIP.ClientID%>").value.substring(i,i+1);
if (digits.indexOf(temp)==-1)
{
alert("Please enter correct zip code");
document.getElementById("<%=txtZIP.ClientID%>").focus();
return false;
}
}
return true;
}
</script>
{
if (document.getElementById("<%=txtName.ClientID%>").value=="")
{
alert("Name Feild can not be blank");
document.getElementById("<%=txtName.ClientID%>").focus();
return false;
}
if(document.getElementById("<%=txtEmail.ClientID %>").value=="")
{
alert("Email id can not be blank");
document.getElementById("<%=txtEmail.ClientID %>").focus();
return false;
}
var emailPat = /^(\".*\"|[A-Za-z]\w*)@(\[\d{1,3}(\.\d{1,3}){3}]|[A-Za-z]\w*(\.[A-Za-z]\w*)+)$/;
var emailid=document.getElementById("<%=txtEmail.ClientID %>").value;
var matchArray = emailid.match(emailPat);
if (matchArray == null)
{
alert("Your email address seems incorrect. Please try again.");
document.getElementById("<%=txtEmail.ClientID %>").focus();
return false;
}
if(document.getElementById("<%=txtWebURL.ClientID %>").value=="")
{
alert("Web URL can not be blank");
document.getElementById("<%=txtWebURL.ClientID %>").value="http://"
document.getElementById("<%=txtWebURL.ClientID %>").focus();
return false;
}
var Url="^[A-Za-z]+://[A-Za-z0-9-_]+\\.[A-Za-z0-9-_%&\?\/.=]+$"
var tempURL=document.getElementById("<%=txtWebURL.ClientID%>").value;
var matchURL=tempURL.match(Url);
if(matchURL==null)
{
alert("Web URL does not look valid");
document.getElementById("<%=txtWebURL.ClientID %>").focus();
return false;
}
if (document.getElementById("<%=txtZIP.ClientID%>").value=="")
{
alert("Zip Code is not valid");
document.getElementById("<%=txtZIP.ClientID%>").focus();
return false;
}
var digits="0123456789";
var temp;
for (var i=0;i<document.getElementById("<%=txtZIP.ClientID %>").value.length;i++)
{
temp=document.getElementById("<%=txtZIP.ClientID%>").value.substring(i,i+1);
if (digits.indexOf(temp)==-1)
{
alert("Please enter correct zip code");
document.getElementById("<%=txtZIP.ClientID%>").focus();
return false;
}
}
return true;
}
</script>
protected void Page_Load(object sender, EventArgs e)
{
btnSubmit.Attributes.Add("onclick", "return validate()");
}
Subscribe to:
Posts (Atom)