gpt4 book ai didi

jquery - MVC3 ModelClientValidationRule 比较 2 个不同的字段。添加一个必需的标志到

转载 作者:行者123 更新时间:2023-12-01 04:57:00 25 4
gpt4 key购买 nike

我正在尝试使用 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com