[英]Is there any “built-in” way to do field-specific, server-side AJAX validation in MVC5? If not, are there any helpers that can assist with this?
I often find myself wanting to validate individual form fields on the fly in MVC5 and while I like the DataAnnotations
I do not think they offer a way to perform server-side validation out of the box. 我经常发现自己想在MVC5中即时验证单个表单字段,尽管我喜欢DataAnnotations
,但我认为它们没有提供开箱即用地执行服务器端验证的方法。
I realize that the validation will be performed on submission anyway but there are certain fields, like username
, which the user should be able to see on-the-fly whether they are valid or not. 我意识到无论如何都将在提交时执行验证,但是有某些字段(例如username
,用户应该能够即时查看它们是否有效。 So I keep on writing jQuery/Javascript code to check these fields with $.ajax
or similar, and it's a lot of boilerplate code writing. 因此,我继续编写jQuery / Javascript代码以使用$.ajax
或类似的代码检查这些字段,这是很多样板代码的编写。 IE, after the appropriate event (input changed) is fired, the client makes a call to the server, then updates a validation placeholder to the right of the field with a checkmark if valid and a bad image if invalid. IE,在触发了适当的事件(更改了输入)之后,客户端将调用服务器,然后使用对勾标记(如果有效)和错误图像(无效)来更新字段右侧的验证占位符。
What bothers me even more is that there is no static type-checking, so I won't know about any egregious syntax errors (ie mis-spelled div id's) until runtime. 更让我困扰的是,没有静态的类型检查,所以直到运行时我都不会知道任何严重的语法错误(即,div id拼写错误)。
I would like to know: 我想知道:
[Required]
field, except it needs to get a response from the server to proceed)? 是否可以编写一个自定义属性来在提交时调用服务器(就像它需要一个[Required]
字段一样,除了需要从服务器获取响应才能继续)? This would be the best option. 这将是最佳选择。 Ajax
call on some appropriate even (say, onChange
) and then update a div after grabbing the result? 是否有任何内置的助手可以在某个适当的偶数(例如onChange
)上进行Ajax
调用,然后在获取结果后更新div? Thanks in advance for any and all advice. 在此先感谢您提供任何建议。
You can use the RemoteAttribute . 您可以使用RemoteAttribute 。
You specify a method on the controller to be called every time the value changes,and return true if its valid,or error messagee if its not. 您可以在每次值更改时在控制器上指定要调用的方法,如果有效,则返回true,否则,则返回错误消息。
In your model: 在您的模型中:
[Remote("IsUserNameUnique", "User")]
public string UserName { get; set; }
Controller: 控制器:
public class UserController : Controller
{
public JsonResult IsUserNameUnique(string UserName)
{
if(isUnique(UserName))
return Json(true,JsonRequestBehavior.AllowGet);
else
retuen Json("Username is taken.",JsonRequestBehavior.AllowGet)
}
}
And if your view you just put 如果您的观点是
@Html.ValidationMessageFor(model=>model.UserName)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.