简体   繁体   English

WCF的企业库6验证:自定义验证器错误消息

[英]Enterprise Library 6 Validation for WCF: Custom Validator Error Message

I am using Enterprise Library 6 Validation in WCF. 我在WCF中使用Enterprise Library 6 Validation。 I have made a Custom Validator. 我做了一个自定义验证器。 When I use it I specify a MessageTemplate . 使用它时,我指定一个MessageTemplate When error Occurs, instead of showing MessageTemplate it shows the message given in DoValidate of the custom validator. 发生错误时,不显示MessageTemplate而是显示自定义验证程序的DoValidate中给出的消息。

Custom Validator 自定义验证器

public sealed class EmailValidatorAttribute : ValidatorAttribute
{
    protected override Validator DoCreateValidator(Type targetType)
    {
        return new EmailValidator();
    }
}

public sealed class EmailValidator : Validator
{
    public EmailValidator()
        : base("Email Validation", "String")
    {
    }
    protected override string DefaultMessageTemplate
    {
        get { return "Email Validation"; }
    }
    // This method does the actual validation
    public override void DoValidate(object objectToValidate, object currentTarget, string key, ValidationResults validationResults)
    {
        Regex emailRegex = new Regex(IConnect.DataContract.WCFServiceResources.EmailRegex);
        Match match = emailRegex.Match((string)objectToValidate);
        if (!match.Success)
        {
            LogValidationResult(validationResults, "Invalid Email Address.", currentTarget, key);
        }
    }
}

WCF WCF

[OperationContract]
[FaultContract(typeof(ValidationFault))]
string EmailAddressCheck([EmailValidator(MessageTemplate = "Enter a Valid Email ID.")]string email);

Currently it is showing "Invalid Email Address." 当前它显示“无效的电子邮件地址”。 defined in DoValidate of Custom Validator Code 在自定义验证程序代码的DoValidate中定义

But

I want to show "Enter a Valid Email ID." 我想显示“输入有效的电子邮件ID”。 defined in MessageTemplate in WCF Code 在WCF代码的MessageTemplate中定义

How to do so? 怎么做?

Finally I found answer to my question. 终于我找到了问题的答案。

public override void DoValidate(
    object objectToValidate,
    object currentTarget,
    string key,
    ValidationResults validationResults)
{
    Regex emailRegex = new Regex(IConnect.DataContract.WCFServiceResources.EmailRegex);
    Match match = emailRegex.Match((string)objectToValidate);
    if (!match.Success)
    {
        LogValidationResult(
           validationResults,
           // The next line does the trick
           string.Format(this.MessageTemplate, new object[] { objectToValidate }),
           currentTarget,
           key);
    }
}

The part in LogValidationResult that does the trick is: LogValidationResult中完成此功能的部分是:

string.Format(this.MessageTemplate, new object[] { objectToValidate })

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM