- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在尝试使用 IClientValidatable
创建自定义验证
我有 2 个字段“电话号码”和“手机”。我希望用户选择其中之一或两者。仅需要 1 个,但必须至少提供一个。
到目前为止我已经做到了
public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
var rule = new ModelClientValidationRule
{
ErrorMessage = FormatErrorMessage(metadata.GetDisplayName()),
ValidationType = "required",
};
rule.ValidationParameters.Add("phone", "PhoneNumber");
rule.ValidationParameters.Add("mobile", "MobileNumber");
yield return rule;
}
这会将验证应用于输出的 html 元素
<input data-val="true" data-val-length="Mobile number must be a maximum length of 14." data-val-length-max="14" data-val-required="Landline or mobile phone number is needed." data-val-required-required="MobileNumber" id="MobileNumber" name="MobileNumber" type="text" value="">
<input data-val="true" data-val-length="Landline number must be a maximum length of 14." data-val-length-max="14" data-val-required="Landline or mobile phone number is needed." data-val-required-required="PhoneNumber" id="PhoneNumber" name="PhoneNumber" type="text" value="">
现在我知道这还不是全部。但如果我尝试点击提交按钮,验证就会启动,并在我的摘要中显示 2 个验证错误。
我对如何添加验证器适配器有点困惑。
到目前为止......我知道它是错的,但是
jQuery.validator.unobtrusive.adapters.add('required',
[$("#PhoneNumber").val(), $("#MobileNumber").val()],
function(options) {
options.rules['required'] = options.params;
options.messages['required'] = options.message;
});
最佳答案
首先,您需要以与 Compare attribute 类似的方式创建自己的验证属性。 .
在此属性中,您将指定其他依赖属性,并且错误消息的格式将考虑属性显示名称。
该属性将如下所示(我对它的名称和默认错误消息不太自豪!):
public class SelectOneValidationAttribute : ValidationAttribute, IClientValidatable
{
private const string DefaultErrorMessage = "Please enter '{0}' or '{1}'.";
private string _otherFieldName;
public SelectOneValidationAttribute(String otherFieldName)
: base(DefaultErrorMessage)
{
_otherFieldName = otherFieldName;
}
public override string FormatErrorMessage(string name)
{
return String.Format(CultureInfo.CurrentCulture, ErrorMessageString, name, _otherFieldName);
}
protected override DataAnnotationsValidationResult IsValid(object value, ValidationContext validationContext)
{
PropertyInfo otherPropertyInfo = validationContext.ObjectType.GetProperty(_otherFieldName);
if (otherPropertyInfo == null)
{
return new DataAnnotationsValidationResult("Unknown property " + _otherFieldName);
}
string strValue = value == null ? null : value.ToString();
if(!String.IsNullOrEmpty(strValue))
//validation succeeds as this field has been populated
return null;
object otherPropertyValue = otherPropertyInfo.GetValue(validationContext.ObjectInstance, null);
string strOtherPropertyValue = otherPropertyValue == null ? null : otherPropertyValue.ToString();
if (!String.IsNullOrEmpty(strOtherPropertyValue))
//validation succeeds as the other field has been populated
return null;
else
//validation failed, none of the 2 fields were populated
return new DataAnnotationsValidationResult(DefaultErrorMessage);
}
//Create the data attributes for the client to use
public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
var rule = new ModelClientValidationRule
{
ValidationType = "selectone",
ErrorMessage = FormatErrorMessage(metadata.GetDisplayName())
};
rule.ValidationParameters["otherfield"] = FormatPropertyForClientValidation(_otherFieldName);
yield return rule;
}
public static string FormatPropertyForClientValidation(string property)
{
return "*." + property;
}
}
因此您可以在模型中使用它,如下所示:
public class YourModel
{
[SelectOneValidation("Phone")]
public string Mobile { get; set; }
[SelectOneValidation("Mobile")]
public string Phone { get; set; }
}
使用该代码时,会出现错误消息“请输入‘手机’或‘电话’。”和“请输入‘电话’或‘手机’。”当服务器端验证失败时将显示。 (您可以在两者上设置相同的错误消息,例如“请输入一个...”)
为了添加客户端验证,您需要创建用于非侵入性验证的适配器。 (确保在不显眼的验证解析文档之前将其添加到某处,否则您将需要手动解析它):
//Add an adaptor for our new jquery validator, that builds the optional parameters
//for our validation code (the other field to look at)
$.validator.unobtrusive.adapters.add("selectone", ["otherfield"], function (options) {
var prefix = getModelPrefix(options.element.name),
other = options.params.otherfield,
fullOtherName = appendModelPrefix(other, prefix),
element = $(options.form).find(":input[name=" + fullOtherName + "]")[0];
setValidationValues(options, "selectone", element);
});
这使用了一些在不显眼的验证库中定义的实用函数,例如:
function setValidationValues(options, ruleName, value) {
options.rules[ruleName] = value;
if (options.message) {
options.messages[ruleName] = options.message;
}
}
function getModelPrefix(fieldName) {
return fieldName.substr(0, fieldName.lastIndexOf(".") + 1);
}
function appendModelPrefix(value, prefix) {
if (value.indexOf("*.") === 0) {
value = value.replace("*.", prefix);
}
return value;
}
最后我创建了一个新的验证规则。这是因为,尽管所需的验证允许设置过滤表达式,因此仅当该表达式计算为 true 时,该字段才会被标记为有效,请参阅 required validation ,我们需要对 onBlur 验证应用与 equalto 规则类似的修复。
验证方法是应用 equalto 验证中的上述修复,然后仅在其他相关字段上使用依赖选择器调用 required 规则,因此仅当字段为空且依赖项不存在时,required 验证才返回 false已满。
$.validator.addMethod("selectone", function (value, element, param) {
// bind to the blur event of the target in order to revalidate whenever the target field is updated
// TODO find a way to bind the event just once, avoiding the unbind-rebind overhead
var otherField = $(param);
if (this.settings.onfocusout) {
otherField.unbind(".validate-selectone").bind("blur.validate-selectone", function () {
$(element).valid();
});
}
var otherFieldBlankFilter = ":input[name=" + otherField[0].name + "]:blank";
return $.validator.methods.required.call(this, value, element, otherFieldBlankFilter);
});
如果您不介意这一点,就好像您仅在提交表单时进行验证一样,您可以编写一个直接使用所需规则的适配器:
$.validator.unobtrusive.adapters.add("selectone", ["otherfield"], function (options) {
var prefix = getModelPrefix(options.element.name),
other = options.params.otherfield,
fullOtherName = appendModelPrefix(other, prefix),
element = $(options.form).find(":input[name=" + fullOtherName + "]")[0];
setValidationValues(options, "required", ":input[name=" + fullOtherName + "]:blank");
});
完成所有这些后,您的验证应该可以正常工作。如果两者均为空并且您尝试提交,这两个字段都会显示错误消息。如果您随后在其中之一中输入内容并按 Tab 键退出,则两条错误消息都应被删除。
您还应该能够根据您的需要进行调整,因为您可以修改验证属性、不显眼的适配器和验证规则。
关于jquery - MVC3 ModelClientValidationRule 比较 2 个不同的字段。添加一个必需的标志到,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13751113/
我想使用 NetworkX Graph 对象作为 Python dict 中的键。但是,我不希望默认的比较行为(即通过对象的地址)。相反,我希望同构图是 dict 中相同元素的键。 此行为是否已在某处
这个问题已经有答案了: What is the most effective way for float and double comparison? (33 个回答) 已关闭 7 年前。 在您认为我
我正在学习 C 编程,为了练习,我找到了一个需要解决的任务。这有点像一个游戏,有人选择一个单词,其他人猜测字母。我必须检查有多少给定的单词可能是所选单词的正确答案。 输入: 3 3//数字 n 和 m
我两天前开始学习C,在做作业时遇到了问题。我们的目的是从字符数组中获取字符列表,并通过计算连续字符并将其替换为数字来缩短它。对“a4b5c5”说“aaaabbbbbccccc”。这是我到目前为止的代码
已关闭。此问题需要 debugging details 。目前不接受答案。 编辑问题以包含 desired behavior, a specific problem or error, and the
为什么我在 if 中的比较不起作用?答案应该是 8 但它返回 0。 function findMissing(missingArray){ var getArray = missing
我想知道为什么以下 JavaScript 比较会给出不同的结果。 (1==true==1) true (2==true==2) false (0==false==0) false (0==false)
我想知道是否有人可以帮助我完成这个程序。编写一个接受两个字符串的函数。该函数应该将这两个字符串与字典顺序上排在第一位的字符串组合起来。两个字符串之间应该有一个空格。在一行上打印结果字符串。在一行上打印
有谁知道一个免费的开源库(实用程序类),它允许您比较一个 Java bean 的两个实例并返回一个属性列表/数组,这两个实例的值不同?请发布一个小样本。 干杯 托马斯 最佳答案 BeanCompara
我是java新手。任何人都可以给出以下类声明的含义 public class ListNode, V> { K key; V value; ListNode next;
我需要用 C 语言计算和比较 3 种不同大小(100 * 100、1000 * 1000 和 10000 * 10000)的 2 个矩阵相乘的执行时间。我编写了以下简单代码来为 1000 * 1000
当我在 ACCESS 2007 中运行以下 SQL 时 Select Location, COUNT(ApartmentBuildings) AS TotalIBuildingsManaged Fro
根据我对互斥锁的了解——它们通常提供对共享资源的锁定功能。因此,如果一个新线程想要访问这个锁定的共享资源——它要么退出,要么必须不断轮询锁(并在等待锁时浪费处理器周期)。 但是,监视器具有条件变量,它
通常在编程中,不应该比较浮点数据类型是否相等,因为存储的值通常是近似值。 由于两个非整数 Oracle NUMBER 值的存储方式不同(以 10 为基数),是否可以可靠地比较它们是否相等? 最佳答案
使用 PowerShell 时,我们偶尔会比较不同类型的对象。一个常见的场景是 $int -eq $bool (即其中 0 -eq $false 、 0 -ne $true 和任何非零值仅等于真,但不
#include #define MAX 1000 void any(char s1[], char s2[], char s3[]); int main() { char string1[
我想比较两个日期。 从这两个日期中,我只使用 ToShortDateString() 获取日期组件, 如下所示。现在的问题是当我比较两个日期时。它的 throw 错误—— "Operator >= c
用户输入一个数字( float 或整数),并且它必须大于下限。 这是从 UITextField 获取数字的代码: NSNumberFormatter * f = [[NSNumberFormatter
我已经摆弄这段代码大约一个小时了,它让我难以置信。我认为解决方案相当简单,但我似乎无法弄清楚。无论如何,这里去。我制作了一个 javascript 函数来检查用户输入的字符,以便它只能接受 7 个字符
我不太明白为什么当我们在不覆盖 equals 的情况下比较具有相同类属性的两个实例时方法,它将给出 false .但它会给出 true当我们比较一个案例类的两个实例时。例如 class A(val
我是一名优秀的程序员,十分优秀!