Form Validation in ASP.NET

.NET Development

The following notes were taken during a lecture in COMP 241 .NET Web Applications at Camosun College by Rob Thorndyke.  These notes are here mainly to help me study, but if you can find some guidance through them then all the better!

Client Side Form Validation

  • No post back
    • Faster
    • More responsive
    • Eases server load
    • .NET Validation Framework
  • If it fails on client:
    • PostBack is cancelled
    • Predefined error message is shown
    • If desired, focus is put into the input control that failed

Server Side Form Validation

  • More secure
  • Access to DB
  • If succeeds on client:
    • ServerValidation event is fired
      • Executes AFTER Load() event; before any control event
  • If validation fails on the server:
    • IsValid property set to false
      • Code: if (! IsValid) return;
  • Then the client responds:
    • Displays predetermined error message
    • If desired, sets focus to the failed input control

Validation Controls in ASP.NET

  • Attached to an input control
  • RequiredFieldValidator
    • Ensures the input text is not blank (whitespace)
    • Optionally ensure a default has been changed!
  • CompareValidator
    • Tests <, <=, ==, >=, >, !=
    • Uses ValueToCompare or ControlToCompare and Operator
    • Eg. Password confirmation
    • Test against a fixed value, or the value in another control
    • Not just for numeric values: Set type property to Convert test values to any supported type first
  • RangeValidator
    • Value falls between “MinimumValue” and “MaximumValue” (inclusive)
    • Again Type == string is assumed! So make sure to set the type if needed.
  • RegularExpressionValidator
    • Set “ValidationExpression”
    • Eg. ^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$
  • CustomValidator
    • Client side: set ClientFunctionName property
      • Must be written in javascript
      • Function myValidatorFunction(source, arguments)
        • Source: validator control
        • Arguments: object with Value field and IsValid field
    • Server side: ServerValidate event handler
      • Public void CustomValidator1_ServerValidate(object source, ServerValidateEventArgs args) {
        • Args.Value, args.IsValid
  • ValidationSummary control
    • Automatically accumulates the error messages from all failed validates
    • Displays them together: list, bullets, paragraph

Setting up .NET Validation Controls

  1. Drag Validator to where you want to see the error message
  2. Configure the Validator to catch whatever is relevant
  3. Set ControlToValidate
  4. Set ErrorMessage
  5. Set Display => None, Static, Dynamic
  6. Set Text to show something always. Eg “*”
Bookmark and Share
No Comments

Leave a Reply

Allowed tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="">