在MVC中的字段验证 [英] Field Validations in MVC
问题描述
我想执行我在我的工作的MVC应用程序查看现场验证。例如 -
I would like to enforce field validations on my Views in the MVC app that I am working on. For example -
- 限制字段的长度为40
- 确保只有字母数字和特殊字符@#$%&放大器; *()-_ +] [';:?,!可以输入
我用下面的限制字段长度:
I used the following to restrict the field length:
<div>
<%= Html.TextBoxFor(c => c.CompanyName, new { style = "width:300px", maxlength = "40" })%></div>
我如何确保只有字母数字和特殊字符可以在文本框输入?
How do I ensure that only alphanumeric and special characters can be entered in the textboxes?
编辑:
我改变了我的模型的属性。
I changed the property in my model to
[DataMember(EmitDefaultValue = false)]
[Required(ErrorMessage="CompanyName is Required")]
[StringLength(40, ErrorMessage = "Must be under 40 characters")]
public string CompanyName { get; set; }
要测试我试图挽救一个空白的公司名称希望能得到一个服务器错误,因为它是必需的。然而,这样可以节省空公司名称。 ?任何想法可能丢失
To test I tried saving a blank CompanyName hoping to get a Server Error since it is Required. However, it saves the blank Company Name. Any ideas what might be missing?
推荐答案
只要创建一个视图模型对象是这样的:
Just create a ViewModel object like this:
class Company
{
[Required]
[StringLength(40)]
[RegularExpression(@"someregexhere")]
public string CompanyName { get; set; }
}
和绑定您查看该模型。通过这种方式,你会同时拥有服务器端和客户方的验证。这真的很容易。
And bind your View to that model. In this way you'll have both serverside and clientside validation. It's really easy.
@model Company
@using (Html.BeginForm()) {
Html.EditorFor(x => x.CompanyName)
<input type="submit" value="Save" />
}
呵呵,这个示例使用剃刀(MVC3),BTW MVC2的作品几乎是同样据我所知。
Oh, this example uses Razor (MVC3), btw MVC2 works pretty much the same as far as I know.
然后,只需通过检查ModelState.IsValid验证在你的控制器传入的视图模型。
Then just validate the incoming ViewModel in your controller by checking ModelState.IsValid.
这篇关于在MVC中的字段验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!