asp.net-mvc - MVC4 : Manually set the validation message from the server side

标签 asp.net-mvc validation

我想在服务器端验证某些表单字段,但是我不想使用数据注释自定义验证器。
我需要根据返回的“业务层方法”的定义来手动设置其值,以定义此消息。

举个例子!

需要:

如果给定的用户名已经存在,则MVC4验证错误范围应显示“此用户名已存在”。

代码:

 if (_business.UserNameExists(username))
 {
    // Set the field validation error span message
    // HOW TO DO??
 }

最佳答案

一位 friend 提供了解决方案,这很简单!

 if (_business.UserNameExists(username))
 {
    // Set the field validation error span message
    ModelState.AddModelError("UserName", "This username already exists.");
 }

其中UserName是要验证的Entity属性的名称。

关于asp.net-mvc - MVC4 : Manually set the validation message from the server side,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11553159/

相关文章:

jquery - 检测通过邮政编码查找自动填充的输入字段中的值更改

c# - 将 Razor View 返回到 Iframe

asp.net-mvc - 如何在大型 asp.net mvc 项目中管理路由

asp.net-mvc - ASP.NET Web API 错误 : No HTTP resource was found that matches the request URI

java - Spring MVC 中的验证

javascript - 使用日期时间选择器进行日期和时间验证 (ASP.Net MVC Core v1.1)

java - 如何使用 IText 确定文本的人工粗体样式和人工轮廓样式

asp.net-mvc - 如何在单个 MVC View 中显示多个表中的数据

javascript - 如何在 asp.net 中使用 JavaScript 只打印表数据元素?

javascript - 在 JavaScript 中验证