[Example Code]: Simple Validation Framework
Recently, I built a simple validation framework which can work with WPF. I found I can use class attribute and reflection to achieve this purpose.
Firstly, I define a Required Attribute to see whether the property requires a value
Code
[AttributeUsage(AttributeTargets.All)] | |
public class RequiredAttribute : System.Attribute | |
{ | |
public readonly bool Required; | |
| |
public RequiredAttribute(bool required) | |
{ | |
this.Required = required; | |
} | |
| |
} |
Then I add IsValid method in the class, it will use the reflect to get all properties in this class. Then it will check whether the property has "required=true", if that is the case, it will check whether the property has value, if not, it will use an error.
public class PersonModel
{
[Required(true)]
public string Name {get;set;}
public IList IsValid()
{
IList ret = new List();
foreach (var prop in this.GetType().GetProperties())
{
foreach(Attribute attr1 in prop.GetCustomAttributes(typeof(RequiredAttribute),true)){
RequiredAttribute attr = (RequiredAttribute) attr1;
if (attr != null) {
if (attr.Required)
{
if (string.IsNullOrEmpty(Convert.ToString(prop.GetValue(this, null)))) {
ret.Add(string.Format("{0} is required",prop.Name));
}
}
}
}
}
return ret;
}
}
is the best practice. I cannot think another way can do it easier.
Please click here to download the example code.
Trackback address for this post
Trackback URL (right click and copy shortcut/link location)
Feedback awaiting moderation
This post has 85 feedbacks awaiting moderation...
Form is loading...