[Last Call] Learn how to a build a cloud-first strategyRegister Now

  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 309
  • Last Modified:

HTML5 Form - MVC - require email format

I have an MVC5 app in which I create a ViewModel to populate a form.  I would like to require that one of the fields have a valid email address.  I have decorated the relevant field as follows in the ViewModel:

[Required, MaxLength(100), DataType(DataType.EmailAddress), Display(Name="Email From")]
        public string EmailFrom { get; set; }

Open in new window

The required field is written as follows in the chtml page:

                <div class="control-group">
                    @Html.LabelFor(model => model.EmailFrom, new { @class = "control-label" })
                    @Html.TextBoxFor(model => model.EmailFrom, null, new { @class = "help-inline form-control" })
                    @Html.ValidationMessageFor(model => model.EmailFrom, null, new { @class = "help-inline" })

Open in new window

The code works as far as requiring something to be entered - but lets me enter a non-valid email field.  any help in fixing this would be greatly appreciated.

1 Solution
käµfm³d 👽Commented:
So long as you understand that you are only validating structure, not that an email actually exists, this should suffice:

[Required, MaxLength(100), DataType(DataType.EmailAddress), Display(Name="Email From"), RegularExpression(@"(?i)^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$")]
public string EmailFrom { get; set; }

Open in new window

The above includes a RegularExpression data annotation that uses a slight modification of the pattern found at:  http://www.regular-expressions.info/email.html
RBSAuthor Commented:
Perfect - I understand - and thanks!


Featured Post

NEW Veeam Agent for Microsoft Windows

Backup and recover physical and cloud-based servers and workstations, as well as endpoint devices that belong to remote users. Avoid downtime and data loss quickly and easily for Windows-based physical or public cloud-based workloads!

Tackle projects and never again get stuck behind a technical roadblock.
Join Now