- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我刚刚创建了一个示例 MVC3 应用程序来学习验证。它正在使用数据注释。我创建了一个名为 CustomStartLetterMatch 的自定义 ValidationAttribute。它正在实现“System.Web.Mvc.IClientValidatable”。我有相应的客户端代码,用不显眼的 jQuery 编写。这按预期工作。
关于自定义验证器:它比较名字输入和姓氏输入。如果两者的第一个字符不相同,则会抛出错误。
正如我所说,该应用程序运行良好。但是当我查看 rule.ValidationType = "greaterdate";
时,我感到困惑。我想将其更改为其他内容,例如“anotherDefaultType”。当我更改它时,它失败并出现 jQuery 错误。
代码:
using System;
using System.ComponentModel.DataAnnotations;
using System.Collections.Generic;
namespace MyValidationTEST
{
public class Person
{
[Required(ErrorMessage = "First name required")]
public string FirstName { get; set; }
[CustomStartLetterMatch("FirstName")]
[StringLength(5,ErrorMessage = "Must be under 5 characters")]
public string LastName { get; set; }
[Range(18,50,ErrorMessage="Must be between 18 and 50")]
public int Age { get; set; }
}
public sealed class CustomStartLetterMatch : ValidationAttribute, System.Web.Mvc.IClientValidatable
{
private const string _defaultErrorMessage = " First letter of '{0}' must be same as first letetr of '{1}'";
private string _basePropertyName;
public CustomStartLetterMatch(string basePropertyName)
: base(_defaultErrorMessage)
{
_basePropertyName = basePropertyName;
}
//Override FormatErrorMessage Method
public override string FormatErrorMessage(string name)
{
return string.Format(_defaultErrorMessage, name, _basePropertyName);
}
//Override IsValid
protected override ValidationResult IsValid(object value, System.ComponentModel.DataAnnotations.ValidationContext validationContext)
{
//Get PropertyInfo Object
var basePropertyInfo = validationContext.ObjectType.GetProperty(_basePropertyName);
var baseValue = (string)basePropertyInfo.GetValue(validationContext.ObjectInstance, null);
var currentValue = (string)value;
string firstLetterBaseValue = baseValue.Substring(0, 1);
string firstLetterCurrentValue = currentValue.Substring(0, 1);
//Comparision
if (!string.Equals(firstLetterBaseValue, firstLetterCurrentValue))
{
var message = FormatErrorMessage(validationContext.DisplayName);
return new ValidationResult(message);
}
//Default return - This means there were no validation error
return null;
}
public IEnumerable<System.Web.Mvc.ModelClientValidationRule> GetClientValidationRules(System.Web.Mvc.ModelMetadata metadata, System.Web.Mvc.ControllerContext context)
{
var rule = new System.Web.Mvc.ModelClientValidationRule();
rule.ErrorMessage = FormatErrorMessage(metadata.GetDisplayName());
rule.ValidationParameters.Add("other", _basePropertyName);
rule.ValidationType = "greaterdate";
yield return rule;
}
}
}
查看
@model MyValidationTEST.Person
@{
ViewBag.Title = "Create";
}
<h2>Create</h2>
<script src="@Url.Content("~/Scripts/jquery-1.5.1.min.js")" type="text/javascript"> </script>
@*UnObtrusive*@
<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
<script type="text/javascript">
/*Register adapter - addSingleVal*/
jQuery.validator.unobtrusive.adapters.addSingleVal("greaterdate", "other");
/*Validation type names in unobtrusive client validation rules must consist of only lowercase letters*/
/*Add Method*/
jQuery.validator.addMethod("greaterdate",
function (val, element, other)
{
var modelPrefix = element.name.substr(0, element.name.lastIndexOf(".") + 1)
var otherVal = $("[name=" + modelPrefix + other + "]").val();
if (val && otherVal)
{
var lastNameFirstLetter = val.substr(0, 1);
var firstNameFirstLetter = otherVal.substr(0, 1);
if (lastNameFirstLetter != firstNameFirstLetter)
{
return false;
}
}
return true;
});
</script>
@using (Html.BeginForm()) {
@Html.ValidationSummary(true)
<fieldset>
<legend>Person</legend>
<div class="editor-label">
@Html.LabelFor(model => model.FirstName)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.FirstName)
@Html.ValidationMessageFor(model => model.FirstName)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.LastName)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.LastName)
@Html.ValidationMessageFor(model => model.LastName)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.Age)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Age)
@Html.ValidationMessageFor(model => model.Age)
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
<div>
@Html.ActionLink("Back to List", "Index")
</div>
Controller :
using System.Web.Mvc;
namespace MyValidationTEST.Controllers
{
public class RelativesController : Controller
{
// GET: /Relatives/
public ActionResult Index()
{
return View();
}
// GET: /Relatives/Create
public ActionResult Create()
{
Person person = new Person();
return View(person);
}
// POST: /Relatives/Create
[HttpPost]
public ActionResult Create(Person relativeToAdd)
{
if (ModelState.IsValid)
{
return RedirectToAction("Index");
}
return View(relativeToAdd);
}
}
}
阅读:
ASP.NET MVC3 - Custom validation attribute -> Client-side broken
最佳答案
I wanted to change it to something else like "anotherDefaultType"
您只能对 ValidationType 属性使用小写字母:
rule.ValidationType = "anotherdefaulttype";
然后调整您的客户端脚本以反射(reflect)此修改:
jQuery.validator.unobtrusive.adapters.addSingleVal("anotherdefaulttype", "other");
jQuery.validator.addMethod("anotherdefaulttype", function (val, element, other) {
...
});
关于jquery - ASP.NET MVC3 : ValidationType ModelClientValidationRule,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9349766/
我已将 vs 2011 开发人员预览版与 vs 2010 并排安装。现在,当我在 vs 2010 中运行我的 asp.net mvc 3 项目时,我在使用 ModelClientValidationR
是否可以直接使用哪些验证规则类型,而无需编写新的代码? 例如 JQuery.validation 有“min(value)” 但是我试过了 var rule = new ModelClientVali
我刚刚创建了一个示例 MVC3 应用程序来学习验证。它正在使用数据注释。我创建了一个名为 CustomStartLetterMatch 的自定义 ValidationAttribute。它正在实现“S
我下载了example written in asp.net mvc3 visual studio 2010的源代码 通过 打开解决方案文件视觉工作室 2012 .它将源代码转换为 2012 并打开解
我正在尝试使用 IClientValidatable 创建自定义验证 我有 2 个字段“电话号码”和“手机”。我希望用户选择其中之一或两者。仅需要 1 个,但必须至少提供一个。 到目前为止我已经做到了
我尝试在 MVC 5 项目中进行自定义客户端验证。当我添加以下代码时: public IEnumerable GetClientValidationRules(ModelMetadata metad
我正在尝试在类库中编写一些客户端验证。我在本地计算机上添加了对 System.Web.Mvc 的引用 C:\Program Files (x86)\Microsoft ASP.NET\ASP.NET
我正在尝试在 VS2010 中“构建”我的 MVC3 Web 应用程序,但不断收到以下错误: 错误 2 类型“System.Web.Mvc.ModelClientValidationRule”存在于“
我是一名优秀的程序员,十分优秀!