vborutenko
vborutenko

Reputation: 4443

Validate first element in list

I have viewmodel like this

public class MyViewModel
{
    public List<string> SubSiteNames { get; set; }
}

In view I do this

    @for (int i = 1; i <= 3; i++)
    {
        <label>Name </label>
        @Html.TextBoxFor(m => m.SubSiteNames[i - 1])
    }

The problem with validation.I need that first element will be required.How can I achieve it?

Note:

I want provide Validation.When user click submit,the message "The name is required" is appeared for first textbox

Upvotes: 1

Views: 1195

Answers (2)

Zabavsky
Zabavsky

Reputation: 13640

It's a bit complicated to make only the first item in the collection required. I suggest you creating a separate property for that and mark it as required:

ViewModel

public class MyViewModel
{
    [Required]
    public string RequiredName { get; set; }
    public List<string> SubSiteNames { get; set; }
}

View

<label>Name </label>
@Html.TextBoxFor(m => m.RequiredName)
@Html.ValidationMessageFor(m => m.RequiredName)
@for (int i = 1; i <= 3; i++)
{
    <label>Name </label>
    @Html.TextBoxFor(m => m.SubSiteNames[i - 1])
}

Then just remove the first item from the SubSiteNames list and set it to the RequiredName.

Upvotes: 0

Nitin Varpe
Nitin Varpe

Reputation: 10694

You can write Custom DataAnnotation for List to not have first element null

public class MustHaveFirstElementAttribute : ValidationAttribute
{
    public override bool IsValid(object value)
    {
        var list = value as IList;
        if (list != null)
        {
            return list[0] != null;
        }
        return false;
    }
}

      [MustHaveFirstElementAttribute (ErrorMessage = "First Element is required")]
        public List<YourClass> SubSiteNames{ get; private set; }

If u want to do it with jquery

 @for (int i = 1; i <= 3; i++)
    {
        <label>Name </label>
        @Html.TextBoxFor(m => m.SubSiteNames[i - 1],new { id="site"+i.ToString()})
    }

Then on submit in jquery

    $("#submit").click(function(e){

     if($("site1").val()=="")
       {
         alert("Invalid");
        e.preventDefault();
       }
});

Upvotes: 1

Related Questions