6

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; }
2
  • How do you want to validate the array ? It must be at least one element ? Or every element should be not null or empty ? Commented Nov 3, 2015 at 9:19
  • Implement IValidatableObject on the model and perform custom validation in there. Alternatively do it within your controller and record the errors using ModelState.AddModelError() Commented Nov 3, 2015 at 9:25

2 Answers 2

10

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; }
Sign up to request clarification or add additional context in comments.

Comments

1

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

2 Comments

You need to check for null before doing the for loop
Our goal not check null value. Need check empty string.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.