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; }

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

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; }

Method 2

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);
    }


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x