Frage

I have a required message and I want to give it a custom message because the default one is not great. The message must come from a resource file and is parametrized, so the message in the resource file will be something like

"The {0} field is required."

I need to be able to replace {0} with something I supply. I know the default message is similar but the problem is I end up with things like

"The RequiredReason field is required."

when what I want is

"The required reason field is required".

Any idea how this can be done?

War es hilfreich?

Lösung

You could make your own RequiredAttribute, and then override the FormatErrorMessage method to use the parameter name or even pass in the parameters you want to format to the class through the constructor.

Something like:

public class ParameterisedRequiredAttribute : RequiredAttribute
    {
        private string[] _replacements { get; set; }

        public ParameterisedRequiredAttribute(params string[] replacements)
        {
            _replacements = replacements;

            ErrorMessageResourceName = ErrorMessagesErrors.SpecificFieldRequired;
            ErrorMessageResourceType = typeof(ErrorMessages);
        }

        public override string FormatErrorMessage(string name)
        {
            return string.Format(ErrorMessageString, (object[])_replacements);
        }
    }
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top