Search code examples
asp.net-mvcvalidationoxite

What is the purpose of suffixes .RequiredError, .FormatError, etc


Reading the Oxite source code, I have found that validators save bad property name with some suffixes (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."));

What is the purpose of whose suffixes? How they used?


Solution

  • My guess is that they're constant, machine-friendly values that can be used to uniquely identify the error and can be used to fetch localized resources for your globalized site.


    I'm a good guesser:

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

    Curious, though. Since exceptions generally shouldn't be localized.