1

In my view model I have the following:

[Required]
[Display(Name = "Email")]
[DataType(DataType.EmailAddress)]
public string[] EmailAddresses { get; set; }

and in my view

for (int i = 0; i < Model.EmailAddresses.Length; i++)
{
  <div class="form-group">
    @Html.LabelFor(m => m.EmailAddresses[i], new {@class = "col-md-2 control-label"})
      <div class="col-md-10">
        @Html.TextBoxFor(m => m.EmailAddresses[i], new { @class = "form-control" })
      </div>
  </div>
}

I want all of the email addresses to adhere to the data type DataType.EmailAddress and have the label Email. I also want at least one email address to be required.

Is this possible to accomplish using attributes?

tereško
  • 58,060
  • 25
  • 98
  • 150
Måns Tånneryd
  • 503
  • 4
  • 9

1 Answers1

0

You can have Custom Attribute for Array Validation for atleast one element - Reference taken from here

    public class RequiredArray : ValidationAttribute
    {
        public override bool IsValid(object value)
        {
            var arr = value as string[];
            if (arr == null)
            {
                return false;
            }

            foreach (var str in arr)
                if (!String.IsNullOrWhiteSpace(str))
                    return true;

            return false;
        }
    }

And in the model -

public class EmailModel
{
    [RequiredArray(ErrorMessage = "At least one email is required")]
    [Display(Name = "Email")]
    [DataType(DataType.EmailAddress)]
    public string[] EmailAddresses { get; set; }
}

To display the same display name for all the Email fields, there is a small work aroung, you can bind EmailAddress directly to the LabelFor.

@using (Html.BeginForm("Click", "Email", FormMethod.Post))
{
    for (int i = 0; i < Model.EmailAddresses.Length; i++)
    {
        <div class="form-group">
            @Html.LabelFor(m => m.EmailAddresses, new { @class = "col-md-2 control-label" })
            <div class="col-md-10">
                @Html.TextBoxFor(m => m.EmailAddresses[i], new { @class = "form-control" })
            </div>
        </div>
    }

    <input type="submit" value="Click" />
}

Output would be when you do not have any emails -

enter image description here

When you have atleast one email -

enter image description here

Community
  • 1
  • 1
ramiramilu
  • 17,044
  • 6
  • 49
  • 66
  • I marked this as the answer, since it does answer my question, but actually ended up wrapping the email address in another class, setting the attributes on the wrapped email string in that class. – Måns Tånneryd Feb 03 '14 at 07:39