2015-04-16 163 views
1

我在WCF中使用Enterprise Library 6验证。我做了一个自定义验证器。当我使用它时,我指定MessageTemplate。发生错误时,不显示MessageTemplate它显示自定义验证程序的DoValidate中给出的消息。企业库6 WCF验证:自定义验证器错误消息

自定义验证

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

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

目前它显示“电子邮件地址无效。”DoValidate自定义验证码的定义

我想表明“输入有效的电子邮件ID。”MessageTemplate定义的WCF代码

怎么办呢?

回答

1

最后我找到了我的问题的答案。

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); 
    } 
} 

的部分LogValidationResult该做的伎俩是:

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