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

在做数据层处理时,我们会为输入的数据做有效性验证,ActiveRecord 为我们提供了如下的验证:

ValidateCreditCard

ValidateDate

ValidateDateTime

ValidateDecimal

ValidateDouble

ValidateEmail

ValidateLength

ValidateNonEmpty

ValidateReg

使用验证

   1:  [ActiveRecord("Comments")]
   2:  public class Comment : ActiveRecordValidationBase<Comment>
   3:  {
   4:      [PrimaryKey("CommentId")]
   5:      public int Id { get; set; }
   6:   
   7:      [Property]
   8:      [ValidateNonEmpty]
   9:      
  10:      public string Text { get; set; }
  11:   
  12:      [Property]
  13:      [ValidateNonEmpty]
  14:      public string Author { get; set; }
  15:   
  16:      [Property]
  17:      public DateTime DateAdded { get; set; }
  18:   
  19:      [BelongsTo("PostId")]
  20:      public Post Post { get; set; }
  21:   
  22:  }

注意:Comment类需要继承于ActiveRecordValidationBase,引用Castle.Components.Validator命名空间

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

IsValid()   验证是否通过

ValidationErrorMessages    获取验证错误信息数组

调用验证

   1:  Comment comment=new Comment ();
   2:  comment.Author=e.CommentAuthor;
   3:  comment.Text=e.CommentText;
   4:  comment.DateAdded = DateTime.Now;
   5:  comment.Post = _service.FindPostBy(_postId);
   6:  if (comment.IsValid())
   7:  {
   8:      _service.AddComment(comment);
   9:  }
  10:  else
  11:  {
  12:      Exception ex = new Exception(comment.ValidationErrorMessages[0]);
  13:      throw ex;
  14:  }

相关文章:

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

posted @ 2012-12-11 21:34  Ian.w  阅读(285)  评论(0编辑  收藏  举报