Castle ActiveRecord学习实践(8):数据有效性的验证

摘要:在我们录入数据时,对数据有效性的验证是必不可少的, ActiveRecord中如何去验证数据的有效性呢?本文将详细介绍这一内容。

 

主要内容

1.概述

2.使用Validation

3.如何扩展

4.深入分析验证

一.概述

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

n         ValidateEmail

n         ValidateIsUnique

n         ValidateRegExp

n         ValidateNotEmpty

n         ValidateConfirmation

 

二.如何使用

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

None.gif [ActiveRecord( " Customs " )]
None.gif
None.gif
public   class  Custom : ActiveRecordValidationBase
None.gif
ExpandedBlockStart.gifContractedBlock.gif
dot.gif {
InBlock.gif
InBlock.gif    
//
InBlock.gif

ExpandedBlockEnd.gif}


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

方法|属性

说明

IsValid()

返回验证是否通过

ValidationErrorMessages

获取验证错误信息数组

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

None.gif [ActiveRecord( " Customs " )]
None.gif
None.gif
public   class  Custom : ActiveRecordValidationBase
None.gif
ExpandedBlockStart.gifContractedBlock.gif
dot.gif {
InBlock.gif
InBlock.gif    
InBlock.gif
InBlock.gif    
private int _id;
InBlock.gif
InBlock.gif    
InBlock.gif
InBlock.gif    
private string _name;
InBlock.gif
InBlock.gif    
InBlock.gif
InBlock.gif    
private string _email;
InBlock.gif
InBlock.gif    
InBlock.gif
InBlock.gif    
private string _address;
InBlock.gif
InBlock.gif    
InBlock.gif
InBlock.gif    
private string _post;
InBlock.gif
InBlock.gif    
InBlock.gif
InBlock.gif    
private string _phone;
InBlock.gif
InBlock.gif    
InBlock.gif
InBlock.gif    [PrimaryKey(PrimaryKeyType.Native)]
InBlock.gif
InBlock.gif    
public int ID
InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif    
dot.gif{
InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif        
get dot.gifreturn this._id; }
InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif        
set dot.gifthis._id = value; }
InBlock.gif
ExpandedSubBlockEnd.gif    }

InBlock.gif
InBlock.gif    
InBlock.gif
InBlock.gif    [Property,ValidateNotEmpty]
InBlock.gif
InBlock.gif    
public string Name
InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif    
dot.gif{
InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif        
get dot.gifreturn this._name; }
InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif        
set dot.gifthis._name = value; }
InBlock.gif
ExpandedSubBlockEnd.gif    }

InBlock.gif
InBlock.gif    
InBlock.gif
InBlock.gif    [Property,ValidateEmail]
InBlock.gif
InBlock.gif    
public string Email
InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif    
dot.gif{
InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif        
get dot.gifreturn this._email; }
InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif        
set dot.gifthis._email = value; }
InBlock.gif
ExpandedSubBlockEnd.gif    }

InBlock.gif
InBlock.gif    
InBlock.gif
InBlock.gif    [Property]
InBlock.gif
InBlock.gif    
public string Address
InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif    
dot.gif{
InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif        
get dot.gifreturn this._address; }
InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif        
set dot.gifthis._address = value; }
InBlock.gif
ExpandedSubBlockEnd.gif    }

InBlock.gif
InBlock.gif    
InBlock.gif
InBlock.gif    [Property,ValidateRegExp(
@"\d{6}")]
InBlock.gif
InBlock.gif    
public string Post
InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif    
dot.gif{
InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif        
get dot.gifreturn this._post; }
InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif        
set dot.gifthis._post = value; }
InBlock.gif
ExpandedSubBlockEnd.gif    }

InBlock.gif
InBlock.gif    
InBlock.gif
InBlock.gif    [Property,ValidateRegExp(
@"(\(\d{3,4}\)|\d{3,4}-)?\d{8}")]
InBlock.gif
InBlock.gif    
public string Phone
InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif    
dot.gif{
InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif        
get dot.gifreturn this._phone; }
InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif        
set dot.gifthis._phone = value; }
InBlock.gif
ExpandedSubBlockEnd.gif    }

InBlock.gif
InBlock.gif    
InBlock.gif
InBlock.gif    
public static void DeleteAll()
InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif    
dot.gif{
InBlock.gif
InBlock.gif        ActiveRecordBase.DeleteAll(
typeof(Custom));
InBlock.gif
ExpandedSubBlockEnd.gif    }

InBlock.gif
InBlock.gif    
InBlock.gif
InBlock.gif    
public static Custom[] FindAll()
InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif    
dot.gif{
InBlock.gif
InBlock.gif        
return ((Custom[])(ActiveRecordBase.FindAll(typeof(Custom))));
InBlock.gif
ExpandedSubBlockEnd.gif    }

InBlock.gif
ExpandedBlockEnd.gif}


编写一些简单的测试代码,大家有兴趣可以看一下:

None.gif [Test]
None.gif
None.gif
public   void  TestNameValidation()
None.gif
ExpandedBlockStart.gifContractedBlock.gif
dot.gif {   
InBlock.gif
InBlock.gif    
//姓名为空
InBlock.gif

InBlock.gif    Custom custom 
= new Custom();
InBlock.gif
InBlock.gif    custom.Address 
= "TianJin";
InBlock.gif
InBlock.gif    custom.Email 
= "lhj_cauc@hotmail.com";
InBlock.gif
InBlock.gif    custom.Phone 
= "022-24096356";
InBlock.gif
InBlock.gif    custom.Post 
= "300192";
InBlock.gif
InBlock.gif    
InBlock.gif
InBlock.gif    
//错误消息数
InBlock.gif

InBlock.gif    
int expectedError = 1;
InBlock.gif
InBlock.gif 
InBlock.gif
InBlock.gif    Assert.IsFalse(custom.IsValid());
InBlock.gif
InBlock.gif    Assert.AreEqual(expectedError,custom.ValidationErrorMessages.Length);
InBlock.gif
ExpandedBlockEnd.gif}

None.gif
None.gif 
None.gif
None.gif[Test]
None.gif
None.gif
public   void  TestPostValidation()
None.gif
ExpandedBlockStart.gifContractedBlock.gif
dot.gif {
InBlock.gif
InBlock.gif    
//邮政编码错误、Email错误
InBlock.gif

InBlock.gif    Custom custom 
= new Custom();
InBlock.gif
InBlock.gif    custom.Name 
= "Terry Lee";
InBlock.gif
InBlock.gif    custom.Email 
= "lhj_cauc#hotmail.com";
InBlock.gif
InBlock.gif    custom.Phone 
= "022-24096356";
InBlock.gif
InBlock.gif    custom.Post 
= "222t";
InBlock.gif
InBlock.gif    custom.Address 
= "Tianjin";
InBlock.gif
InBlock.gif 
InBlock.gif
InBlock.gif    
//错误消息数
InBlock.gif

InBlock.gif    
int expectedError = 2;
InBlock.gif
InBlock.gif    
InBlock.gif
InBlock.gif    Assert.IsFalse(custom.IsValid());
InBlock.gif
InBlock.gif    Assert.AreEqual(expectedError,custom.ValidationErrorMessages.Length);
InBlock.gif
ExpandedBlockEnd.gif}

None.gif
None.gif 
None.gif
None.gif[Test]
None.gif
None.gif
public   void  TestAllValidation()
None.gif
ExpandedBlockStart.gifContractedBlock.gif
dot.gif {   
InBlock.gif
InBlock.gif    
//全部正确
InBlock.gif

InBlock.gif    Custom custom 
= new Custom();
InBlock.gif
InBlock.gif    custom.Name 
= "Terry Lee";
InBlock.gif
InBlock.gif    custom.Email 
= "lhj_cauc@hotmail.com";
InBlock.gif
InBlock.gif    custom.Phone 
= "022-24096335";
InBlock.gif
InBlock.gif    custom.Address 
= "TianJin";
InBlock.gif
InBlock.gif    custom.Post 
= "300192";
InBlock.gif
InBlock.gif 
InBlock.gif
InBlock.gif    
//错误消息数
InBlock.gif

InBlock.gif    
int expectedError = 0;
InBlock.gif
InBlock.gif    
InBlock.gif
InBlock.gif    Assert.IsTrue(custom.IsValid());
InBlock.gif
InBlock.gif    Assert.AreEqual(expectedError,custom.ValidationErrorMessages.Length);
InBlock.gif
ExpandedBlockEnd.gif}

 

三.如何扩展

上面这些验证已经能够满足我们绝大多数的需求,但是我们也可以去添加自己的验证。来看看ActiveRecord中的Validation的类结构图(只画出了部分)

通过上图可以看到,如果想添加自己的验证,需要有一个继承AbstractValidator和继承于AbstractValidationAttribute的类就可以了,具体可以参考ActiveRecord的代码。

 

四.深入分析验证

通过上面的分析我们都知道所有的实体类都继承于ActiveRecordValidationBase基类,那么ActiveRecord是如何通过特性来进行验证的呢?下面我们结合源码进一步分析一下。

我们在属性上加上了验证, Attribute并不做任何实质性的工作,它只是调用验证器进行验证,先来看一下ValidateNotEmptyAttribute的代码:

None.gif [Serializable]
None.gif
None.gif
public   class  ValidateNotEmptyAttribute : AbstractValidationAttribute
None.gif
ExpandedBlockStart.gifContractedBlock.gif
dot.gif {
InBlock.gif
InBlock.gif    
public ValidateNotEmptyAttribute() : base(new NullCheckValidator())
InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif    
dot.gif{
InBlock.gif
ExpandedSubBlockEnd.gif    }

InBlock.gif
InBlock.gif 
InBlock.gif
InBlock.gif    
public ValidateNotEmptyAttribute(String errorMessage) : base(new NullCheckValidator(), errorMessage)
InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif    
dot.gif{
InBlock.gif
InBlock.gif 
InBlock.gif
ExpandedSubBlockEnd.gif    }

InBlock.gif
ExpandedBlockEnd.gif}


所有验证工作都是在Validator中进行的,以NullCheckValidator为例来看它做了什么操作:

 

None.gif [Serializable]
None.gif
None.gif
public   class  NullCheckValidator : AbstractValidator
None.gif
ExpandedBlockStart.gifContractedBlock.gif
dot.gif {
InBlock.gif
InBlock.gif    
public NullCheckValidator()
InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif    
dot.gif{
InBlock.gif
InBlock.gif 
InBlock.gif
ExpandedSubBlockEnd.gif    }

InBlock.gif
InBlock.gif 
InBlock.gif
InBlock.gif    
public override bool Perform(object instance, object fieldValue)
InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif    
dot.gif{
InBlock.gif
InBlock.gif        
return fieldValue != null && fieldValue.ToString().Length != 0;
InBlock.gif
ExpandedSubBlockEnd.gif    }

InBlock.gif
InBlock.gif 
InBlock.gif
InBlock.gif    
protected override string BuildErrorMessage()
InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif    
dot.gif{
InBlock.gif
InBlock.gif        
return String.Format("{0} is not optional.", Property.Name);
InBlock.gif
ExpandedSubBlockEnd.gif    }

InBlock.gif
ExpandedBlockEnd.gif}


这个类其实很简单,但我们注意到有一个Perform的方法,正是这个方法完成了验证工作,拿这个例子来说,如果字段的值为空或长度等于零就返回false,否则为true。对于正则验证等其他的也都是在这个方法中完成。回到ActiveRecordValidationBase中去,看这个类初始化的时候做了什么操作?

 

ExpandedBlockStart.gif ContractedBlock.gif /**/ /// <summary>
InBlock.gif
InBlock.gif
/// Constructs an ActiveRecordValidationBase
InBlock.gif
ExpandedBlockEnd.gif
/// </summary>

None.gif
None.gif
public  ActiveRecordValidationBase()
None.gif
ExpandedBlockStart.gifContractedBlock.gif
dot.gif {
InBlock.gif
InBlock.gif    CollectValidators( 
this.GetType() );
InBlock.gif
ExpandedBlockEnd.gif}

None.gif
None.gif 
None.gif
ExpandedBlockStart.gifContractedBlock.gif
/**/ /// <summary>
InBlock.gif
InBlock.gif
/// Collect the validations applied to this class properties.
InBlock.gif
InBlock.gif
/// </summary>
InBlock.gif
ExpandedBlockEnd.gif
/// <param name="targetType"></param>

None.gif
None.gif
private   void  CollectValidators( Type targetType )
None.gif
ExpandedBlockStart.gifContractedBlock.gif
dot.gif {
InBlock.gif
InBlock.gif    ActiveRecordModel model 
= GetModel( targetType );
InBlock.gif
InBlock.gif 
InBlock.gif
InBlock.gif    
if (model == null)
InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif    
dot.gif{
InBlock.gif
InBlock.gif        
throw new ActiveRecordException("Seems that the framework wasn't initialized properly. (ActiveRecordModel could not obtained)");
InBlock.gif
ExpandedSubBlockEnd.gif    }

InBlock.gif
InBlock.gif 
InBlock.gif
InBlock.gif    __validators.AddRange( model.Validators );
InBlock.gif
InBlock.gif 
InBlock.gif
InBlock.gif    
while( model.Parent != null )
InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif    
dot.gif{
InBlock.gif
InBlock.gif        __validators.AddRange( model.Parent.Validators );
InBlock.gif
InBlock.gif 
InBlock.gif
InBlock.gif        model 
= model.Parent;
InBlock.gif
ExpandedSubBlockEnd.gif    }

InBlock.gif
ExpandedBlockEnd.gif}

 

在初始化的时候,通过ActiveRecordModel获取到当前实体所有属性对应的Validator,并放在了一个ArrayList中去,然后在IsValid()方法中再逐一调用ValidatorPerform()方法来判断验证是否通过,因为所有的验证器都实现了Ivalidator。如果有验证发生错误,则把错误信息保存再一个字符数组中,可以通过属性ValidationErrorMessages来获取错误信息。

 

None.gif public   bool  IsValid()
None.gif
ExpandedBlockStart.gifContractedBlock.gif
dot.gif {
InBlock.gif
InBlock.gif    ArrayList errorlist 
= new ArrayList();
InBlock.gif
InBlock.gif    __failedProperties 
= new Hashtable();
InBlock.gif
InBlock.gif 
InBlock.gif
InBlock.gif    
foreach(IValidator validator in __validators)
InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif    
dot.gif{
InBlock.gif
InBlock.gif        
if (!validator.Perform(this))
InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif
InBlock.gif            String errorMessage 
= validator.ErrorMessage;
InBlock.gif
InBlock.gif            
InBlock.gif
InBlock.gif            errorlist.Add( errorMessage );
InBlock.gif
InBlock.gif 
InBlock.gif
InBlock.gif            ArrayList items 
= null;
InBlock.gif
InBlock.gif 
InBlock.gif
InBlock.gif            
if (__failedProperties.Contains(validator.Property))
InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif
InBlock.gif                items 
= (ArrayList) __failedProperties[validator.Property];
InBlock.gif
ExpandedSubBlockEnd.gif            }

InBlock.gif
InBlock.gif            
else
InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif
InBlock.gif                items 
= new ArrayList();
InBlock.gif
InBlock.gif 
InBlock.gif
InBlock.gif                __failedProperties[validator.Property] 
= items;
InBlock.gif
ExpandedSubBlockEnd.gif            }

InBlock.gif
InBlock.gif 
InBlock.gif
InBlock.gif            items.Add(errorMessage);
InBlock.gif
ExpandedSubBlockEnd.gif        }

InBlock.gif
ExpandedSubBlockEnd.gif    }

InBlock.gif
InBlock.gif 
InBlock.gif
InBlock.gif    _errorMessages 
= (String[]) errorlist.ToArray( typeof(String) );
InBlock.gif
InBlock.gif 
InBlock.gif
InBlock.gif    
return errorlist.Count == 0;
InBlock.gif
ExpandedBlockEnd.gif}

ActiveRecord中的数据有效性验证就介绍到这儿了,下篇我会介绍ActiveRecord常用的一些技巧。[非常感谢idior大哥提出的意见]

 

参考资料

Castle 的官方网站http://www.castleproject.org
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值