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

Answers


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

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.


Need Your Help

Data Annotation Ranges of UK Datetime fields

asp.net-mvc datetime data-annotations

I want to use Data Annotations to validate DateTime fields, but I'm running into problems. According to documentation on MSDN (http://msdn.microsoft.com/en-us/library/system.componentmodel.

how does gdb attach to multithread process

c++ c multithreading gdb ptrace

When we use gdb attach to debug a running process, we could use gdb attach pid ,if the process have two or more threads, the pid is the main thread tid.