I use ASP.NET MVC. How can i validate string array in my view model. Because "Required" attribute doesn't work with string array.
[DisplayName("Content Name")]
[Required(ErrorMessage = "Content name is required")]
public string[] ContentName { get; set; }
You can create a custom validation attribute : http://www.codeproject.com/Articles/260177/Custom-Validation-Attribute-in-ASP-NET-MVC
public class StringArrayRequiredAttribute : ValidationAttribute
{
protected override ValidationResult IsValid (object value, ValidationContext validationContext)
{
string[] array = value as string[];
if(array == null || array.Any(item => string.IsNullOrEmpty(item)))
{
return new ValidationResult(this.ErrorMessage);
}
else
{
return ValidationResult.Success;
}
}
}
Then you can use like this :
[DisplayName("Content Name")]
[StringArrayRequired(ErrorMessage = "Content name is required")]
public string[] ContentName { get; set; }
You should use custom validate
[HttpPost]
public ActionResult Index(TestModel model)
{
for (int i = 0; i < model.ContentName.Length; i++)
{
if (model.ContentName[i] == "")
{
ModelState.AddModelError("", "Fill string!");
return View(model);
}
}
return View(model);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With