MVC驗證06-自訂錯誤資訊

來源:互聯網
上載者:User

標籤:style   blog   http   color   width   os   

原文:MVC驗證06-自訂錯誤資訊

本文體驗自訂錯誤資訊。

  系統預設的錯誤資訊

在"MVC驗證02-自訂驗證規則、郵件驗證"中,我們自訂了一個驗證Email的類。如果輸入郵件格式錯誤,出現系統預設的報錯資訊。

效果:
             

 

  通過ErrorMessage來修改錯誤資訊

[Email(ErrorMessage = "Email格式錯誤")]
[Display(Name = "郵件")]
public string Email { get; set; }

效果:

  在自訂驗證特性中重寫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);
        }
    }
}
 

效果:

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.