I have the following properties in my Model
[Required]
[DataType(DataType.PhoneNumber, ErrorMessage = "Invalid Phone Number")]
public string PhoneNumber
{
get;
set;
}
[Required]
[DataType(DataType.EmailAddress, ErrorMessage = "Invalid Email Address")]
public string EmailAddress
{
get;
set;
}
The corresponding View is
<td>
Email
</td>
<td>
@Html.EditorFor(model => model.EmailAddress)
@Html.ValidationMessageFor(model => model.EmailAddress, "*")
</td>
</tr>
<tr>
<td>
Phone #
</td>
<td>
@Html.TextBoxFor(model => model.PhoneNumber)
@Html.ValidationMessageFor(model => model.PhoneNumber, "*")
</td>
When I render this page I see the Required attribute getting triggered. But the DataType attribute is not getting fired if I key in Invalid data.I see the source html and don't see any code being emitted for these validations. I have the following as a part of my view too
<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"/>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"/>
DataAnnotations is used to configure your model classes, which will highlight the most commonly needed configurations. DataAnnotations are also understood by a number of . NET applications, such as ASP.NET MVC, which allows these applications to leverage the same annotations for client-side validations.
Answers. You have added the Assessment type as a parameter in the post action method. Hence MVC try to create a new instance of Assessment class. If the value for Title field is not provided in the view, then it will try to set the value for Title property as null.
You could consider using ASP.NET MVC 3 Futures. Here is a nice article describing validations there:
public class UserInformation
{
[Required]
public string Name { get; set; }
[Required]
[EmailAddress]
public string Email { get; set; }
[Required]
[Url]
public string Website { get; set; }
[Required]
[CreditCard]
public string CreditCard { get; set; }
[Required]
[FileExtensions(Extensions = "jpg,jpeg")]
public string Image { get; set; }
}
See this post:
Is the DataTypeAttribute validation working in MVC2?
It's important to note that the DataType Attribute is usually used for formatting purposes, not for validation. Technically there are a wide range of email formats and phone number formats (see here for email: http://www.regular-expressions.info/email.html).
Also, custom converters can be made to convert seemingly non-email strings into emails (me at domain dot com = [email protected]), and thus having default validation regexs flies out the window. It is left up to the developer to use the correct regex for their specific purpose, and to ensure they only accept address they believe are accurate.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With