Showing posts with label validations. Show all posts
Showing posts with label validations. Show all posts

Sunday, 9 December 2012

Validation ASP.NET Server Controls

Goals:
  • Present ASP.NET validation controls.
Steps:
  1. Create a new ASP.NET Web Application project in Visual Studio.
  2. Add a Button and a Literal to the page:
    <asp:Button ID="PostbackButton" runat="server" onclick="PostbackButton_Click"
        
    Text="PostbackButton" />
    <
    asp:Literal ID="statusLiteral" runat="server"></asp:Literal>
    Add also code for the PostbackButton_Click method:
    protected void PostbackButton_Click(object sender, EventArgs e)
    {
        statusLiteral.Text =
    "PostbackButton_Click called";
    }
  3. RequiredFieldValidator
    • Add a TextBox control. Add also a RequiredFieldValidator control (from the Validation group in the Toolbox window) attached to this TextBox (using the ControlToValidate property):

      Run the page and note that the validator is hidden initially. It is visible only in case of a try to postback the page with empty value in the TextBox.
      Note also that the red error information displayed by the validator appears immediately. It is done by the JavaScript code used by the validator internally. All built-in validators have both the JavaScript and C# code for validating values provided by the user on the client and server-side, respectively.
    • The RequiredFieldValidator control works also for other types of controls, e.g. for the DropDownList:

      In this case, the InitialValue property of the RequiredFieldValidator control is the most important - it allows to point the default value which should be treated as non-value.
    • Add 2 additional TextBox controls with RequiredFieldValidator controls, but this time in one line, to see an effect of changing value of the Display property of the validator control.

      Run the page once with Static value for the Display property of the validator and once with Dynamic value. Note the difference in placing controls.
  4. ValidationSummary
    • This control is not a validator but a place for displaying all messages coming from validator controls.
    • It uses the ErrorMessage properties of all validator controls. To see it in action, set the Text properties of all used validators to 'Text of [#]' and ErrorMessage to 'ErrorMessage of [#]':
    • Add the ValidationSummary control under the button:
    • See the ValidationSummary control in action:
    • Make some tests - set or delete value either the ErrorMessage or the Text property. Try also to set the Display property to None.
    • Note also other interesting properties of the ValidationSummary control: DisplayMode, ShowMessageBox, and ShowSummary.
  5. Validators can be grouped by values of the ValidationGroup property. This property can be set for validator controls and all controls that can cause validation, in particular Button controls..
    • Modify the ValidationGroup property to value 'ValGroup1' for all existing validators, the ValidationSummary control, and the button.
    • Run the application and verify that there are no changes.
  6. CompareValidator
    • A classic need for a web application is to ask the user for a password and its confirmation:
      • When values of 2 controls should be compared, the ControlToValidate and ControlToCompare properties must be set.
      • Note that the 2nd button and this CompareValidator have the same value for the ValidationGroup property. Because the name is different than the corresponding value for controls from the first group, this group works independently.
      • Note also that when no password is written, the validator does not work. Use a RequiredFieldValidator control to require the user to enter data in the input control.
    • The CompareValidator control can also be used to check type of a value provided by the user. For example, to force the user to write a proper number:
      • In this case the Type and Operator properties are crucial.
      • Note also usage of the SetFocusOnError property.
    • Not only a type but also a value can be validated:
  7. RangeValidator
    • This control is similar to the CompareValidator control. As an example, ask the user for time:
  8. RegularExpressionValidator
    • This control can be very useful when there is a need to test if the user's input matches a string template. For example, check if the user has written a proper email address:
  9. CustomValidator
    • The CustomValidator control allows to provide a custom validation function in JavaScript and a method in C#. As an example, create a validator that will accept only numbers that can be devided by 5.
    • Add a CustomValidator control, Button, and TextBox. Be sure to set the ValidationGroup property:
    • The logic of the client-side and server-side validation is quite simple. The server-side validation is required to ensure that data provided by the user is correct. The client-side validation is desired to give the user an immediate feedback without waiting for the server's response.
    • The server-side validation must be written as a C# event handler for the ServerValidate event of the CustomValidator:
      protected void CustomValidator1_ServerValidate(object source, ServerValidateEventArgs args)
      {
          
      int num;
          
      if (int.TryParse(args.Value, out num) && num % 5 == 0)
          {
              args.IsValid =
      true;
          }
          
      else     {
              args.IsValid =
      false;
          }
      }
    • The client-side validation must be a JavaScript function:
      <script language="JavaScript">
          function
      CustomValidator1_ClientValidate(oSrc, args) {
              args.IsValid = (args.Value % 5 == 0);
          }
      </script>
      and the markup for the CustomValidator:
      <asp:CustomValidator ID="CustomValidator1" runat="server"
          
      ControlToValidate="TextBox11" ErrorMessage="Wrong!"
          
      onservervalidate="CustomValidator1_ServerValidate"
          
      ClientValidationFunction="CustomValidator1_ClientValidate"
          ValidationGroup="ValGroup4">
      </
      asp:CustomValidator>
  10. The text displayed by a validator control can use HTML tags. This feature allows to use in example image to notify the user about an error:

    using the following code:
    <asp:CustomValidator ID="CustomValidator1" runat="server"
       
    ControlToValidate="TextBox11" Display="Dynamic"
       
    ErrorMessage="<img src='exclamation.png' />"
       
    onservervalidate="CustomValidator1_ServerValidate"
       
    ClientValidationFunction="CustomValidator1_ClientValidate"
       
    ValidationGroup="ValGroup4">
[Source code]

Monday, 19 March 2012

JQuery Password Strength indicator Example in asp.net | Display Validation error message with images in asp.net

Introduction:

In this article I will explain how to display images whenever validation fails in form using JQuery and I will explain how to show password strength using JQuery in asp.net.



Description:
  
In previous articles I explained about form validations using JavaScript  and Ajax Password Strength using asp.net . Now I will explain how to show the images when validation fails and I will explain how to show the password strength using JQuery in asp.net.
In one of the website I saw different type of form validations in registration form when we click on submit button without entering any data they are displaying error message with image just beside of particular control and they are displaying password strength based on text entered in textbox. After seen that form I decided to write post to explain how to implement this one using JQuery.

To implement this concept first open Visual Studio and create new website after that right click on your website and add two new folders and give name as Images and JS and insert images and script files in particular folders you should get it from attached folder. After that write the following code in your aspx page 

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>JQuery Validate Form and Show Password Strength</title>
<link href="FormValidation.css" rel="stylesheet" type="text/css" />
<link href="jquery.validate.password.css" rel="stylesheet" type="text/css" />
<script src="JS/jquery.js" type="text/javascript"></script>
<script src="JS/jquery.validate.js" type="text/javascript"></script>
<script src="JS/jquery.validate.password.js" type="text/javascript"></script>
<script language="javascript" type="text/javascript">

$(document).ready(function() {
// validate signup form on keyup and submit
var validator = $("#signupform").validate({
rules: {
username: {
required: true,
minlength: 2
},
password: {
password: "#username"
},
password_confirm: {
required: true,
equalTo: "#password"
},
location: {
required: true
}
},
messages: {
username: {
required: "Enter a username",
minlength: jQuery.format("Enter at least {0} characters")
},
password_confirm: {
required: "Repeat your password",
minlength: jQuery.format("Enter at least {0} characters"),
equalTo: "Enter the same password as above"
},
location: {
required: "Enter a Location"
}
},
// the errorPlacement has to take the table layout into account
errorPlacement: function(error, element) {
error.prependTo(element.parent().next());
},
// set this class to error-labels to indicate valid fields
success: function(label) {
// set &nbsp; as text for IE
label.html("&nbsp;").addClass("checked");
}
});
});
</script>
</head>
<body>
<form id="signupform" runat="server">
<div id="signupwrap">
<table align="center">
<tr>
<td></td>
<td><b>User Registration</b></td>
<td></td>
</tr>
<tr>
<td align="right" class="label">UserName:</td>
<td  class="field"><asp:TextBox ID="username" runat="server"/></td>
<td class="status"></td>
</tr>
<tr>
<td  align="right" class="label">Password:</td>
<td  class="field"><asp:TextBox ID="password" runat="server" TextMode="Password"/></td>
<td class="status" align="left">
<div class="password-meter">
<div class="password-meter-message">&nbsp;</div>
<div class="password-meter-bg">
<div class="password-meter-bar"></div>
</div>
</div>
</td>
</tr>
<tr><td align="right" class="label">Confirm Password:</td>
<td  class="field"><asp:TextBox ID="password_confirm" runat="server" TextMode="Password"/></td>
<td class="status"></td>
</tr>
<tr>
<td align="right" class="label">Location:</td>
<td  class="field"><asp:TextBox ID="location" runat="server"/></td>
<td class="status"></td>
</tr>
<tr>
<td></td>
<td><asp:Button ID="btnSubmit" Text="Submit" runat="server"/></td>
<td></td>
</tr>
<tr>
<td colspan="3" height="20px">
</td>
</tr>
<tr>
<td></td>
<td colspan="2">
<table>
<tr>
<td>UserName:</td>
<td><asp:Label ID="lbluser" runat="server"/></td>
</tr>
<tr>
<td>Password:</td>
<td><asp:Label ID="lblPwd" runat="server"/></td>
</tr>
<tr>
<td>Location:</td>
<td><asp:Label ID="lblLocation" runat="server"/></td>
</tr>
</table>
</td>
</tr>
</table>
</div>
</form>
</body>
</html>
If you observe above code in header section I added some of script files and css files by using those files we have a chance to show password strength based on text entered in textbox and display the images when validation fails using JQuery in asp.net.

Demo

Download sample code attached