zoukankan      html  css  js  c++  java
  • 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):数据有效性的验证

  • 相关阅读:
    IDEA调试快捷键
    视频预览
    文件上传:简单的demo
    Java 运行时优化
    Java 类加载
    Java StringTable
    Java 为什么不用Vector
    C++ 查找函数
    JVM 垃圾回收
    JVM 直接内存
  • 原文地址:https://www.cnblogs.com/whx1973/p/2813702.html
Copyright © 2011-2022 走看看