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

  • 相关阅读:
    TCP 协议三次握手过程解析带实例
    一些关于反汇编与逆向方面的博文分享
    关于mwArray和一般数组的区别
    vc6.0 使用Ado 连接MS-SqlServer2000 连接字符串
    VC6使用技巧
    Oracle性能诊断艺术-读书笔记(执行计划中显示 Starts, E-Rows, REM A-Rows and A-Time)等)
    Oracle性能诊断艺术-读书笔记
    linux 检查补丁包是否安装 名称 版本 release号
    我叫他小北
    Oracle linux安装Oracle 11G
  • 原文地址:https://www.cnblogs.com/darrenji/p/3581320.html
Copyright © 2011-2022 走看看