ASP.NET supplies 6 different validation controls, each with some distinct properties besides the few common ones:
- RequiredFieldValidator
- RangeValidator
- MaximumValue (In code behind, MaximumValue=DateTime.Today.ToString(“yyyy/MM/dd”))
- MinimumValue (1850/1/1)
- Type (String or Date)
- RegularExpressionValidator
- ValidationExpression – put in regular expression here. There are a few of pre-defined ones.
- CompareValidator
- ControlToValidate & ControlToCompare
- CustomValidator
- Double-click on design mode to get the event handler on server-side
e.g. args.IsValid == (args.Value.Length >= 8 ) - clientValidationFunction (JavaScript)
e.g.
function isLengthValid (source, args)
{
args.IsValid = (args.Value.Length >= 8 )
} - Both client- and server-side validation function should be included
- Double-click on design mode to get the event handler on server-side
- ValidationSummary
- HeaderText
- CssClass
- DisplayMode
- Common properties:
-
- ControlToValidate – this is the most essential obvisouly, a must
- ErrorMessage – Text in here will be displayed in the ValidationSummary
- Text – This will be displayed right at where the validation control lies
- Display (Static/Dynamic/None) – pretty intuitive. I see “dynamic” being the default, because it doesn’t take up space when it’s not being validated. There is no reason for some empty place holder.
- EnableClientScript – default is true; if browser supports JavaScript, then validation is done on client first. If the validation fails, then postback is cancelled.
- ValidationGroup – Just give it a name, and give the same name to the button or whatever control that is to trigger the validation, then only the fields with the same group name will be validated.
Uses:
Page.Validate(ValidationGroupPropertyValue) – tells the page to perform validation on fields with that specified validation group
GetValidators(ValidationGroup) – returns a collection of validation controls that belong to the specified validation group - SetFocusOnError – same as the Focus() method; if set to True, causes the Web control the validation control is operating on to receive focus if the validation control is invalid
Example: To validate a password, should use the following validation
- RequiredFieldValidator
- RegularExpressionValidator
- CompareValidator (for the re-type password field)
- CustomValidator (To check length of password)
More references:
- MSDN – ASP.NET Validation in Depth
- MSDN – Validating ASP.NET Server Controls
- ASP.NET Quickstart Tutorials
- Google Password Strength API (CodeProject)
- 4GuysFromRolla – Creating Validator Controls for the CheckBox and CheckBoxList
By Bryan Xu