You need to use the ModelMetadata.Name property and the
ValidationContext.MemberName property to get the
name of the property. Then, you need to use String.Format to convert the value of the object into a string according to the
specified format, and then insert it into
another string.
The following is an example, you can refer to it.
RequiredIfNotAttribute
public class RequiredIfNotAttribute : ValidationAttribute, IClientModelValidator
{
public int v;
public RequiredIfNotAttribute(int v)
{
this.v = v;
}
public void AddValidation(ClientModelValidationContext context)
{
if (context == null)
{
throw new ArgumentNullException(nameof(context));
}
context.Attributes.Add("data-val", "true");
context.Attributes.Add("data-val-required", String.Format(ErrorMessageString,context.ModelMetadata.Name));
}
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
ErrorMessage = String.Format(ErrorMessageString,validationContext.MemberName);
short currentValue = Convert.ToInt16(value);
// validation logic
bool validationPassed = false;
if (!validationPassed)
return new ValidationResult(ErrorMessage);
else
return ValidationResult.Success;
}
}
Model
public class TestCustomModel
{
[Display(Name = "StatusTest")]
[RequiredIfNot(1, ErrorMessage = "{0} is required")]
public short? Status { get; set; }
}
Controller
public class CustomModelController : Controller
{
public IActionResult Index()
{
return View();
}
[HttpPost]
public IActionResult Test(TestCustomModel model)
{
if (ModelState.IsValid)
{
}
return RedirectToAction("Index");
}
}
ASP.NET forums are moving to a new home on Microsoft Q&A, we encourage you to go to Microsoft Q&A for .NET for posting new questions and get involved today. Learn more >
Thanks for the direct and detailed explanation. It worked straight away.
I just made a change to get the Display attribute property (in case it can have other name than actual property name and can have spaces)
Member
7 Points
75 Posts
Show model property name in custom validation
Feb 28, 2021 03:28 PM|vkagrawal|LINK
Hi,
I have a model with few properties and I am adding custom validation on some of its properties. Everything is fine, it is validating as expected.
Only problem I see is in custom validators I am not able to get the model properties name as we can get that with in built validators.
Below is code sample
if I use [RequiredIfNot(1, ErrorMessage = "{0} is required")] then it shows error message as it is '{0} is required' rather than 'Status is required'
I could pass in properties's name using nameof(Status) and replace {0} with that in validator but I want to align with built in validators.
Thanks
Contributor
3040 Points
863 Posts
Re: Show model property name in custom validation
Mar 01, 2021 02:49 AM|YihuiSun|LINK
Hi vkagrawal,
You need to use the ModelMetadata.Name property and the ValidationContext.MemberName property to get the name of the property. Then, you need to use String.Format to convert the value of the object into a string according to the specified format, and then insert it into another string.
The following is an example, you can refer to it.
RequiredIfNotAttribute
Model
Controller
View
Here is the result.
Best Regards,
YihuiSun
Member
7 Points
75 Posts
Re: Show model property name in custom validation
Mar 01, 2021 06:01 PM|vkagrawal|LINK
Hi YihuiSun,
Thanks for the direct and detailed explanation. It worked straight away.
I just made a change to get the Display attribute property (in case it can have other name than actual property name and can have spaces)
Instead of
in client side code, I used
Same thing for service side validation message, instead of
I used
Rest everything worked fine as expected.
Thanks!