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]

No comments :