3

In my model I have:

[Required]
[DataType(DataType.EmailAddress)]
public string EmailAddress {get; set;}

However in my view (source) this renders as:

<label for="EmailAddress">EmailAddress</label>
<input data-val="true" data-val-required="The EmailAddress field is required"
    id="EmailAddress" name="EmailAddress" type="text" value="" />
<span class="field-validation-valid" data-valmsg-for="EmailAddress" data-valmsg-replace="true">

I thought this should have rendered with type="email" rather than type="text" - so when validating on the client side, it does not pickup if the email is not in a valid format.

EDIT

Further more, when I call if (ModelState.IsValid) it returns true, even if the email address is not in the correct format. so even if the browser does not support HTML5, I would have thought that the IsValid in the controller would then have enforced the validation - is that not the case?

Is there something else I need on my model, to force type="email" so this correctly checks for a valid email address?

Thanks you,

Mark

1
  • When creating your project, did you select the option for HTML5? Commented Apr 17, 2013 at 13:29

3 Answers 3

7

The DataType attribute doesn't do any validation or render the email attribute on the input. This question describes how to add email validation using either a regular expression or the Data Annotations Extensions library.

Also if you use @Html.TextBoxFor(m => m.Email, new { type = "email" }) (if using the HTML5 doctype) that will render the email attribute which will cause validation for compatible browsers - see this.

It also has the added advantage that some (most modern) smartphones will show an email keyboard (with @ symbol and .com) for easier typing. See Default To The Numeric, Email, And URL Keyboards On The iPhone.

Sign up to request clarification or add additional context in comments.

Comments

0

This input type is only available in HTML5:

<input type="email" />

You can try to set doctype to HTML5 for your document like this:

<!DOCTYPE html>

EDIT But you won't be sure client browser will be able to treat / validate this input as an email.

1 Comment

Hi - thanks - it is set to HTML5, but obviously mt browser version is not ok with HTML5 - however, when posting back to the controller, I would have expected that would have picked up on the model not being valid?
0

This maybe just what you need. On that page it says that it supports the Email input type.

There is also support for the following input types in the toolkit: Text, Color, Email, Search, Time, Tel, File, Date, Datetime, Month, Week, Range, Number

Comments

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.