3

I want to create an ErrorMessage containing another variable or property value in it. I want to keep it simple. So far this piece of code shows an error for the String.Format parameter. What is the best way to achieve it:

    public class MyClass
    {
        [RequiredIf("IsRequired", true, ErrorMessage=String.Format("The 'something' ({0}) is required because of: {1}", Something, CustomExplanation)]
        public string Something { get; set; }

        [Required]
        public bool IsRequired { get; set; }

        [Required]
        [StringLength(200, MinimumLength=20)]
        public string CustomExplanation { get; set; }
    }

I have already read this question and answer: string.Format in Data Annotation Validation Attributes That's ok, but maybe there is a workaround...

1 Answer 1

4

My suggestion for you is to use FluentValidator. This is very good library to reach you goals.

Link - http://fluentvalidation.codeplex.com/

You can solve your problem with code like this:

RuleFor(m => m.Something).When(m => m.IsRequired).WithMessage("Your message here.");

Please let me know in case of or if you'll have the questions.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.