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):数据有效性的验证

  • 相关阅读:
    java连接mysql以及增删改查操作
    Django中ORM表的创建以及基本增删改查
    python链接mysql以及mysql中对表修改的常用语法
    Windows系统安装MySQL
    php 之 excel导出导入合并
    玄学基础
    ubuntu 17.10 安装QQ
    CI框架导入 excel
    atom插件安装
    excel怎么截取字符串
  • 原文地址:https://www.cnblogs.com/whx1973/p/2813702.html
Copyright © 2011-2022 走看看