Reputation: 103
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...
Upvotes: 3
Views: 817
Reputation: 6527
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.
Upvotes: 4