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
- ServerValidation event is fired
- If validation fails on the server:
- IsValid property set to false
- Code: if (! IsValid) return;
- IsValid property set to false
- 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
- Public void CustomValidator1_ServerValidate(object source, ServerValidateEventArgs args) {
- Client side: set ClientFunctionName property
- ValidationSummary control
- Automatically accumulates the error messages from all failed validates
- Displays them together: list, bullets, paragraph
Setting up .NET Validation Controls
- Drag Validator to where you want to see the error message
- Configure the Validator to catch whatever is relevant
- Set ControlToValidate
- Set ErrorMessage
- Set Display => None, Static, Dynamic
- Set Text to show something always. Eg “*”