zoukankan      html  css  js  c++  java
  • MVC验证06-自定义错误信息

    本文体验自定义错误信息。

      系统默认的错误信息

    在"MVC验证02-自定义验证规则、邮件验证"中,我们自定义了一个验证Email的类。如果输入邮件格式错误,出现系统默认的报错信息。

    效果:
    邮件验证1             

     

      通过ErrorMessage来修改错误信息

    [Email(ErrorMessage = "Email格式错误")]
    [Display(Name = "邮件")]
    public string Email { get; set; }

    效果:
    自定义错误1

      在自定义验证特性中重写FormatErrorMessage方法

    using System.ComponentModel.DataAnnotations;
    using System.Text.RegularExpressions;
    using System.Web.Mvc;
     
    namespace MvcValidation.Extension
    {
        public sealed class EmailAttribute : ValidationAttribute, IClientValidatable
        {
            public const string reg = @"^[w-]+(.[w-]+)*@([w-]+.)+[a-zA-Z]+$";
     
            public EmailAttribute()
            {  
            }
     
            //重写基类方法
            public override bool IsValid(object value)
            {
                if (value == null)
                    return true;
     
                if (value is string)
                {
                    Regex regEx = new Regex(reg);
                    return regEx.IsMatch(value.ToString());
                }
                return false;
            }
     
            public System.Collections.Generic.IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
            {
                ModelClientValidationRule rule = new ModelClientValidationRule
                {
                    ValidationType = "email",
                    ErrorMessage = FormatErrorMessage(metadata.GetDisplayName())
                };
                yield return rule;
            }
     
            /// <summary>
            /// 格式化错误信息
            /// </summary>
            /// <param name="name">属性名</param>
            /// <returns></returns>
            public override string FormatErrorMessage(string name)
            {
                return  this.ErrorMessage ?? string.Format("{0}属性没有输入正确的Email", name);
            }
        }
    }
     

    效果:
    自定义错误2

  • 相关阅读:
    Oracle学习 第29天 存储过程生成报表
    Oracle学习 第28天 存储过程输出结果集
    Python学习 第9天 连接FTP和数据库
    Bat脚本学习-6:Oracle自动备份还原脚本
    Bat脚本学习-5:Oracle自动备份还原脚本
    Bat脚本学习-4:Oracle自动备份还原脚本
    Vue学习 第2天 又看了个教程,加深理解
    Vue学习 第1天 初始Vue及MVVM
    下半年加油,好久没上来冒个泡了
    Python学习 第8天 打包exe
  • 原文地址:https://www.cnblogs.com/darrenji/p/3581320.html
Copyright © 2011-2022 走看看