【发布时间】:2016-09-08 17:41:03
【问题描述】:
我曾经使用此链接MVC3 Validating Multiple Fields As A Single Property 实现多字段必填验证
但它在我的最后没有工作。
下面是我使用的代码。
Javascript
$.validator.addMethod('multifield', function (value, element, params) {
var properties = params.propertyname.split(',');
var isValid = false;
var count = 0;
for (var i = 0; i < properties.length; i++) {
var property = properties[i];
if ($('#' + property).val() != "") {
count++;
}
}
if (properties.length == count) {
isValid = true;
}
return isValid;
}, '');
$.validator.unobtrusive.adapters.add('multifield', ['propertyname'], function (options) {
options.rules['multifield'] = options.params;
options.messages['multifield'] = options.message;
}
);
类
public class Customer
{
public string AreaCode { get; set; }
[MultiFieldRequired(new string[2] { "AreaCode", "PhoneNumber" }, ErrorMessage = "Please enter a phone number")]
public string PhoneNumber { get; set; }
}
public class MultiFieldRequiredAttribute : ValidationAttribute, IClientValidatable
{
string propertyName;
private readonly string[] _fields;
public MultiFieldRequiredAttribute(string[] fields)
{
_fields = fields;
}
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
foreach (string field in _fields)
{
propertyName = field;
PropertyInfo property = validationContext.ObjectType.GetProperty(field);
if (property == null)
return new ValidationResult(string.Format("Property '{0}' is undefined.", field));
var fieldValue = property.GetValue(validationContext.ObjectInstance, null);
if (fieldValue == null || String.IsNullOrEmpty(fieldValue.ToString()))
return new ValidationResult(this.FormatErrorMessage(validationContext.DisplayName));
}
return ValidationResult.Success;
}
public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
// The value we set here are needed by the jQuery adapter
ModelClientValidationRule multifield = new ModelClientValidationRule();
multifield.ErrorMessage = this.ErrorMessage;
multifield.ValidationType = "multifield"; // This is the name the jQuery validator will use
//"otherpropertyname" is the name of the jQuery parameter for the adapter, must be LOWERCASE!
multifield.ValidationParameters.Add("propertyname", string.Join(",", _fields));
yield return multifield;
}
}
查看
@using (Html.BeginForm("Add", "Home", FormMethod.Post, new { @class = "form-inline" }))
{
<div class="editor-label">
@Html.LabelFor(model => model.AreaCode)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.AreaCode)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.PhoneNumber)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.PhoneNumber)
@Html.ValidationMessageFor(model => model.PhoneNumber)
</div>
<button type="submit" tabindex="19" class="form-control btn btn-primary" style="float: right; margin-left: 8px; margin-right: 10px;">Submit</button>
}
【问题讨论】:
-
什么不工作 - 客户端或服务器端验证或两者兼而有之?您已经实现了
IClientValidatable,但没有显示您的脚本以将规则添加到$.validator,这是客户端验证所必需的 -
服务器端和客户端都不起作用。另外我不知道我需要在 javascript 中进行的#.validator 更改
-
要了解客户端验证所需的内容,请参阅The Complete Guide To Validation In ASP.NET MVC 3 - Part 2。但它不是很清楚你想做什么。如果您希望在
PhoneNumber上具有必需的验证属性,同时确保AreaCode具有值,那么您应该将一个属性仅应用于PhoneNumber,并且该属性接受另一个属性的 nae 参数。跨度> -
应该是
return ValidationResult.Success;(不是return null;) -
我也添加了 javascript 代码...您能找到问题并立即解决吗
标签: c# asp.net-mvc-5