Welcome

首页 / 软件开发 / .NET编程技术 / Castle ActiveRecord学习实践(8) 数据有效性的验证

Castle ActiveRecord学习实践(8) 数据有效性的验证2011-02-03 cnblogs terrylee主要内容

1.概述

2.使用Validation

3.如何扩展

4.深入分析验证

一.概述

在录入数据时,对数据有效性的验证是必不可少的,很多时候我们在UI层上就会做一层验证,但有时也需要在底层做一些必要的处理,这就要用到ActiveRecord中的数据有效性的验证。ActiveRecord为我们提供了如下几个验证:

n ValidateEmail

n ValidateIsUnique

n ValidateRegExp

n ValidateNotEmpty

n ValidateConfirmation

二.如何使用

为了使用上面这些验证,我们必须用ActiveRecordValidationBase来代替ActiveRecordBase,即实体类必须继承于ActiveRecordValidationBase。

[ActiveRecord("Customs")]
public class Custom : ActiveRecordValidationBase
{
//
}

ActiveRecordValidationBase类为我们提供了如下一个方法和属性:

方法|属性 说明

IsValid() 返回验证是否通过

ValidationErrorMessages 获取验证错误信息数组

下面看一个完整的例子代码,在这个程序中我们需要验证用户名不能为空,Email地址、邮政编码、电话号码的格式是否正确

[ActiveRecord("Customs")]public class Custom : ActiveRecordValidationBase{private int _id;private string _name;private string _email;private string _address;private string _post;private string _phone;[PrimaryKey(PrimaryKeyType.Native)]public int ID{get { return this._id; }set { this._id = value; }}[Property,ValidateNotEmpty]public string Name{get { return this._name; }set { this._name = value; }}[Property,ValidateEmail]public string Email{get { return this._email; }set { this._email = value; }}[Property]public string Address{get { return this._address; }set { this._address = value; }}[Property,ValidateRegExp(@"d{6}")]public string Post{get { return this._post; }set { this._post = value; }}[Property,ValidateRegExp(@"((d{3,4})|d{3,4}-)?d{8}")]public string Phone{get { return this._phone; }set { this._phone = value; }}public static void DeleteAll(){ActiveRecordBase.DeleteAll(typeof(Custom));}public static Custom[] FindAll(){return ((Custom[])(ActiveRecordBase.FindAll(typeof(Custom))));}}