[英]How to validate error message using c# in asp.net mvc?
I am struggling to validate an empty EditorFor
using Data-Annotation
, have tried using jquery on a client side.我正在努力使用Data-Annotation
验证一个空的EditorFor
,并尝试在客户端使用 jquery 。 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.我希望当用户离开@EditorFor()
显示错误图像时验证此错误的想法。
// 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.正确使用 MVC 的 Data Annotation 可以在没有 JQuery 的情况下实现。
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:要验证有效的 email 地址,可以使用以下注释:
[Required(ErrorMessage = "This field is required")]
[EmailAddress(ErrorMessage = "Invalid email address")]
public string Email { get; set; }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.