Kra*_*ras 26 unobtrusive-validation asp.net-mvc-3
我正在使用标准的MVC3 Razor视图和不显眼的Javascript验证,@Html.ValidationSummary用于在表单的顶部显示它们.如果标准验证(类似的东西[Required])通过,我会运行一些非常自定义的客户端验证,当用户点击提交按钮时会激活该验证.(验证查看了许多表单元素,以确保已经检查了它们的正确集合等,因此它不像仅为单个字段创建新的自定义验证器那么简单).
我希望我在那里构建的可能错误显示在ValidationSummary列表中,但我无法弄清楚如何让错误消息出现在那里.
jav*_*iry 42
在客户端:
function YourCustomValidator() {
// do your validation logic here via JavaScript
return true; // or false based on your validation logic
}
$(document).ready(function () {
// take your own form-selector like ("form", this)
$("form", this).first().submit(function () {
return (YourCustomValidator() && $(this).valid());
});
});
Run Code Online (Sandbox Code Playgroud)
或者在服务器端:
认为你有这样的模型:
public class Test {
[Required]
[StringLength(100)]
public string FullName { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
当你验证它时:
if(ModelState.IsValid) { // default validations run here
if(/* some custom validations run here, there is an error about "FullName" */){
// you should set the "key" for Model-Error to "FullName"
ModelState.AddModelError("FullName","error-message goes here")
}
if(/* some custom validations run here, the error is global, not on "FullName" */){
// you should set the "key" for Model-Error to an empty-string
ModelState.AddModelError("","error-message goes here")
}
// also you can test for model-errors again like this:
if(ModelState.IsValid) { // if you add any error above, this will be "false"
}
}
Run Code Online (Sandbox Code Playgroud)
你可以这样做只是添加Error Message到ModelState应该显示错误消息要告诉你,只要你有ValidationSummary()要求你的看法.
要将错误添加到ModelState刚执行此操作:
ModelState.AddModelError("ColumnNameOrErrorMessageKeyInState","error message goes here")
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
30732 次 |
| 最近记录: |