MVC validation 06-Custom error messages

Source: Internet
Author: User

Original: MVC validation 06-Custom Error message

This article experiences custom error messages.

System default error message

In MVC validation 02-Custom validation rules, message validation, we've customized a class that validates email. If the input message format is wrong, the system default error message appears.

Effect:

To modify the error message by errormessage

"email format error")]
"Mail")]
 Public string Email {get; set;}

Effect:

Overriding the Formaterrormessage method in a custom validation attribute

using System.ComponentModel.DataAnnotations;
using System.Text.RegularExpressions;
using SYSTEM.WEB.MVC;
namespace Mvcvalidation.extension
{
     Public Sealed class Emailattribute:validationattribute, iclientvalidatable
    {
         Public Const string @ "^[\w-]+ (\.[ \w-]+) *@ ([\w-]+\.) +[a-za-z]+$ ";
         Public Emailattribute ()
        {  
        }
        overriding base class methods
         Public Override BOOL IsValid (objectvalue)
        {
            if (valuenull)
                return true;
            if (valueisstring)
            {
                New Regex (REG);
                return regex.ismatch (value. ToString ());
            }
            return false;
        }
         Public System.collections.generic.ienumerable<modelclientvalidationrule> Getclientvalidationrules (ModelMetadata metadata, ControllerContext context)
        {
            New Modelclientvalidationrule
            {
                "Email",
                ErrorMessage = formaterrormessage (metadata. GetDisplayName ())
            };
            yield return rule;
        }
        <summary>
        Formatting error messages
        </summary>
        <param name= "Name" > property name </param>
        <returns></returns>
         Public Override string Formaterrormessage (string name)
        {
            return   This string. Format ("{0} attribute did not enter the correct email", name);
        }
    }
}

Effect:

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.