zoukankan      html  css  js  c++  java
  • 自定义注解

    MaxWordsAttribute.cs

    /*
     自定义注解
     */
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.ComponentModel.DataAnnotations;
    
    namespace MusicStore.Models
    {
        /// <summary>
        /// 自定义最大单词注解
        /// </summary>
        public class MaxWordsAttribute : ValidationAttribute
        {
            private readonly int _maxWords;//最大单词数量
            public MaxWordsAttribute(int maxWords)
                : base("{0} has to many words.")//默认显示的提示消息
            {
                this._maxWords = maxWords;
            }
            protected override ValidationResult IsValid(object value, ValidationContext validationContext)
            {
                if (value != null)
                {
                    var valueAsString = value.ToString();
                    if (valueAsString.Split(' ').Length > _maxWords)
                    {
                        var errorMessage = FormatErrorMessage(validationContext.DisplayName);//替换值占位符,显示属性显示的名称
                        return new ValidationResult(errorMessage);//返回提示消息,如果用户有定义就取用户定义的,如果没定义就取默认的值
                    }
                }
                return ValidationResult.Success;
            }
        }
    }

    /// <summary>
    /// 我的单词
    /// </summary>
    [MaxWords(10,ErrorMessage="{0}已超过最大单词")]
    public string MyWords { get; set; }

    模型自身验证的实现

    TestSelfValidating.cs

    /*
     练习自身模型对象
     */
    using System;
    using System.Collections.Generic;
    using System.ComponentModel.DataAnnotations;
    using System.Linq;
    using System.Web;
    
    namespace MusicStore.Models
    {
        public class TestSelfValidating:IValidatableObject
        {
            public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)//公开枚举对象
            {
                if (Name != null && Name.Length > 10)
                {
                    yield return new ValidationResult("The last name has too many words!", new[] { "Name" });//迭代对个返回枚举值,之所以要用迭代返回多个,因为自身验证是整个模型,所以要返回多个提示消息,后面要跟一个数组,因为可能会包含多个名称
                }
            }
            public string Name { get; set; }
        }
    }

    这样子就能实现自我验证了。

  • 相关阅读:
    Tips for C++ Primer Chapter 11 关联容器
    Tips for C++ Primer Chapter 10 泛型算法
    Tips for C++ Primer Chapter 9 顺序容器
    Tips for C++ Primer Chapter 8 IO库
    Trie Tree 字典树
    Manacher Algorithm 最长回文子串
    【Android Studio】android Internal HTTP server disabled 解决
    释放修改OS X 10.11系统文件权限【转】
    win10 Vmware12装mac os X10.11虚拟机教程
    【Android开发实践】android.view.InflateException: Binary XML file line #12: Error inflating class fragment问题解决
  • 原文地址:https://www.cnblogs.com/frank888/p/4567782.html
Copyright © 2011-2022 走看看