Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validate String Array In ASP.NET MVC

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; }
like image 362
Yargicx Avatar asked Nov 03 '15 09:11

Yargicx


2 Answers

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; }
like image 87
Paul DS Avatar answered Nov 08 '22 12:11

Paul DS


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);
    }
like image 35
Taivan Amgalan Avatar answered Nov 08 '22 14:11

Taivan Amgalan