gpt4 book ai didi

asp.net-mvc - MVC3 不显眼的输入验证组

转载 作者:行者123 更新时间:2023-12-03 06:46:43 27 4
gpt4 key购买 nike

我需要验证 3 个或更多输入字段(至少需要一个)。例如我有电子邮件、传真、电话。

我需要至少填写一项。我需要服务器和客户端“不引人注目的验证”。请帮忙。我研究了“比较”方法并尝试修改它但没有成功。请帮忙。谢谢

最佳答案

您可以编写自定义属性:

public class AtLeastOneRequiredAttribute : ValidationAttribute, IClientValidatable
{
private readonly string[] _properties;
public AtLeastOneRequiredAttribute(params string[] properties)
{
_properties = properties;
}

protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
if (_properties == null || _properties.Length < 1)
{
return null;
}

foreach (var property in _properties)
{
var propertyInfo = validationContext.ObjectType.GetProperty(property);
if (propertyInfo == null)
{
return new ValidationResult(string.Format("unknown property {0}", property));
}

var propertyValue = propertyInfo.GetValue(validationContext.ObjectInstance, null);
if (propertyValue is string && !string.IsNullOrEmpty(propertyValue as string))
{
return null;
}

if (propertyValue != null)
{
return null;
}
}

return new ValidationResult(FormatErrorMessage(validationContext.DisplayName));
}

public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
var rule = new ModelClientValidationRule
{
ErrorMessage = ErrorMessage,
ValidationType = "atleastonerequired"
};
rule.ValidationParameters["properties"] = string.Join(",", _properties);

yield return rule;
}
}

它可以用来装饰你的 View 模型属性之一(如果验证失败你想要突出显示的属性):

public class MyViewModel
{
[AtLeastOneRequired("Email", "Fax", "Phone", ErrorMessage = "At least Email, Fax or Phone is required")]
public string Email { get; set; }
public string Fax { get; set; }
public string Phone { get; set; }
}

然后是一个简单的 Controller :

public class HomeController : Controller
{
public ActionResult Index()
{
var model = new MyViewModel();
return View(model);
}

[HttpPost]
public ActionResult Index(MyViewModel model)
{
return View(model);
}
}

渲染以下 View ,该 View 将负责定义自定义客户端验证器适配器:

@model MyViewModel

<script src="@Url.Content("~/Scripts/jquery.validate.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.js")" type="text/javascript"></script>
<script type="text/javascript">
jQuery.validator.unobtrusive.adapters.add(
'atleastonerequired', ['properties'], function (options) {
options.rules['atleastonerequired'] = options.params;
options.messages['atleastonerequired'] = options.message;
}
);

jQuery.validator.addMethod('atleastonerequired', function (value, element, params) {
var properties = params.properties.split(',');
var values = $.map(properties, function (property, index) {
var val = $('#' + property).val();
return val != '' ? val : null;
});
return values.length > 0;
}, '');
</script>

@using (Html.BeginForm())
{
@Html.ValidationSummary(false)

<div>
@Html.LabelFor(x => x.Email)
@Html.EditorFor(x => x.Email)
</div>

<div>
@Html.LabelFor(x => x.Fax)
@Html.EditorFor(x => x.Fax)
</div>

<div>
@Html.LabelFor(x => x.Phone)
@Html.EditorFor(x => x.Phone)
</div>

<input type="submit" value="OK" />
}

当然,自定义适配器和验证器规则应该外部化到单独的 JavaScript 文件中,以避免将脚本与标记混合。

关于asp.net-mvc - MVC3 不显眼的输入验证组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5816313/

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