0

阅读 Oxite 源代码,我发现验证器使用一些后缀(RequiredError、MaxLengthExceededError、InvalidError、FormatError)保存错误的属性名称

validationState.Errors.Add(CreateValidationError(user.Name, "Name.RequiredError", "Name is not set"));

validationState.Errors.Add(CreateValidationError(user.Name, "Name.MaxLengthExceededError", "Username must be less than or equal to {0} characters long.", 256));

validationState.Errors.Add(CreateValidationError(user.Email, "Email.InvalidError", "Email is invalid."));

谁的后缀的目的是什么?他们是怎么用的?

4

1 回答 1

1

我的猜测是,它们是恒定的、机器友好的值,可用于唯一标识错误,并可用于为您的全球化站点获取本地化资源。


我是一个很好的猜测者:

    protected ValidationError CreateValidationError(
        object value, string validationKey, string validationMessage, 
        params object[] validationMessageParameters)
    {
        if (validationMessageParameters != null && 
            validationMessageParameters.Length > 0)
        {
            validationMessage = string.Format(
              validationMessage, validationMessageParameters);
        }

        return new ValidationError(
            validationKey,
            value,
            new InvalidOperationException(
              localize(validationKey, validationMessage))
            );
    }

    private string localize(string key, string defaultValue)
    {
        if (phrases == null)
            phrases = localizationService.GetTranslations();

        Phrase foundPhrase = phrases
          .Where(p => p.Key == key && p.Language == site.LanguageDefault)
          .FirstOrDefault();

        if (foundPhrase != null)
            return foundPhrase.Value;

        return defaultValue;
    }

不过很好奇。因为异常通常不应该被本地化。

于 2009-06-13T00:26:12.050 回答