When filling out a form, you need to verify the content, check that the data meets the requirements, such as the length of the string, the format of the date, the number, and so on. WPF supports custom validation rules and provides visual feedback to notify users when an invalid value is entered.
The following example demonstrates a process for simulating employee information entry, an integer with an employee's age greater than 18, a number greater than 2500, and a red exclamation mark after the text box if the input is incorrect, and when the mouse moves to the error text box, a prompt message prompts the user for the correct input format.
Validation of data
You can inherit the ValidationRule class, override the Validate method, implement a custom validation rule
The following are the implementations of the Age validation rule:
Public classAgerangerule:validationrule {Private int_min;Private int_max; PublicAgeRangeRule () {} Public intMin {Get{return_min; }Set{_min =value; } } Public intMax {Get{return_max; }Set{_max =value; } } Public OverrideValidationresult Validate (Object value, CultureInfo CultureInfo) {intAge = 0;Try{if(((string)value). Length > 0) Age = Int32.Parse ((String)value); }Catch(Exception e) {return NewValidationresult (false, "the number entered is invalid! "); }if(Age < Min) | | (Age > Max)) {return NewValidationresult (false, "The age range you enter must be in:"+ Min +" - "+ Max +"between"); }Else{return NewValidationresult (true,NULL); } } } View Code
WPF data validation