There are several possible approaches:
- Use "instant" validation.
When user enters value it is checked during input (TextChanged
) and validated right away. Create instance of a new class, call property/method what should accept string
and return bool
(or throw Exception
in case of property), on false
- draw special error condition (red label next to text box, something blinking, ErrorProvider
or whatever you can do what should tell user "wrong!").
This one I like to use, but a bit differently, usually I only check Type
and then just trying to parse it straight away in the form. It is possible to abstract more if form operate with the string
's and all formattings and validation occurs in the class (property setters). Or you can supply form with additional information (by using query methods or attributes) so it can do instant validation without need to instantiate class or using setters. As example, double factor
property can be identified in the form (or even control) to perform 'double.Parseand you can have attribute
DefaultValuewhich can be used to display to the user value in the different way when it's different from default (like it is done by
PropertyGrid`).
When user finished input, validate (by trying to set value and catching exception), if wrong - user can't "leave" or "progress" until he press ESC (to cancel changes) or correct his input to pass validation.
This one I dislike. Idea of holding user annoy me (and user ofc). Also it is hard to implement cross checks (like if you have Min
and Max
values, then user will be pushed to increase "right" one first, otherwise invalidation will fail).
That just means let user to enter everything and only validate when he clicks "Ok" button.
I think combining "Ok" button and interactive instant validation is the best for the user. As user knows where he made a mistake through input, but still is free to browse and only will get a "slap" from validation after clicking "Ok" button (at which step you can simply show him first of errors he did, not necessary to show them all).
Error messages can be provided by setters in the old-fashion LastError
way or as a text in the Exception
.