I am struggling to validate an empty EditorFor
using Data-Annotation
, have tried using jquery on a client side. Somehow I feel it's better to validate it from the back end than front end. Have a look and help me to improve my logic error. The idea I want this error to validate when user leaves the @EditorFor()
showing error image.
// Model
[Required(ErrorMessage = "This field is required")]
public string Email { get; set; }
//View
script type='text/javascript'>
$(function () {
//When the blur event occurs from your Textbox (you lose focus)
$('#textEmail').blur(function () {
var email = document.getElementById("textEmail").value;
var expr = /^([\w-\.]+)@@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;
if (!expr.test(email)) {
alert("Invalid email address.");
}
else {
alert("Ok");
}
});
});
It can be achieved without JQuery by using MVC's Data Annotation properly.
For data annotation, write error message above the property as below:
[Required(ErrorMessage = "This field is required")]
public string Email { get; set; }
Some other annotations are also available along with Required annotation. To validate the valid email address below annotation can be used:
[Required(ErrorMessage = "This field is required")]
[EmailAddress(ErrorMessage = "Invalid email address")]
public string Email { get; set; }
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.