【发布时间】:2015-09-02 18:31:22
【问题描述】:
我已经为表单验证编写了这段代码,它运行良好
数据持有者
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
namespace workflow.DataHolders
{
public class NewCompany
{
[Required]
[StringLength(200, MinimumLength = 3, ErrorMessage="Length Of The Company Name Should Be More Than Three Letters")]
public string CompanyName { get; set; }
[Required]
[EmailAddress(ErrorMessage="Invalid Email Address")]
public string Email { get; set; }
[Required]
[StringLength(200, MinimumLength = 2, ErrorMessage = "Length Of The Country Name Should Be More Than Two Letters")]
public string Country { get; set; }
public string Description { get; set; }
}
}
查看侧面
<link href="@Url.Content("~/sharedfiles/css/forms/addnew.css")" rel="stylesheet" type="text/css" />
<div id="Add_container">
@if (!ViewData.ModelState.IsValid)
{
<div id="validationMessage">Please Correct The Errors Below</div>
}
@using (Html.BeginForm("ValidateAndSignUp", "Accounts", FormMethod.Post))
{
@Html.AntiForgeryToken()
@Html.ValidationMessage("CompanyName");
<span class="field_title">Company Name: </span>
@Html.TextBox("CompanyName")
@Html.ValidationMessage("Email");
<span class="field_title">Email: </span>
@Html.TextBox("Email")
@Html.ValidationMessage("Country");
<span class="field_title">Country Name: </span>
@Html.TextBox("Country")
<span class="field_title">About The Company: </span>
@Html.TextArea("Description")
<input type="submit" value="Create New Account">
}
</div>
<div class="get_connected_message">
<h1>Get Connected with your Customers</h1>
</div>
<div class="get_connected_message">
<h1>Build your profissional buisness world</h1>
</div>
<div class="clear"></div>
ValidateAndSignUp 操作
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult ValidateAndSignUp(NewCompany newCompany)
{
if (ModelState.IsValid)
{
return RedirectToAction("index", "Home");
}
else
{
return View("signUp", newCompany);
}
}
每件事都完美运行并且可以正确验证,但是我尝试了 @Html.validate 方法,因为我读到它没有做任何其他事情,它会注册字段以进行验证,但这意味着什么?这是否意味着它注册它以在客户端进行验证,如果是,如何做到这一点?
【问题讨论】:
-
如果您使用
@Html.ValidationMessage()(或ValidationMessageFor()),则没有理由使用@Html.Validate()(或ValidateFor()) -
@StephenMuecke 是的,我知道,但我想了解它是如何工作的?
-
我认为它强制验证没有@Html.ValidationMessage() 的给定字段,您可以自己显示消息...
标签: jquery validation asp.net-mvc-4