我以前使用這個鏈接實現多字段需要驗證MVC3 Validating Multiple Fields As A Single PropertyMultifield required驗證不適用於MVC 5中的客戶端?
但它沒有在我的結尾工作。
下面是我使用的代碼。
的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更改。 – Gaurav123
要了解客戶端驗證需要什麼,請參閱[ASP.NET MVC 3中的驗證完整指南 - 第2部分](http:/ /www.devtrends.co.uk/blog/the-complete-guide-to-validation-in-asp.net-mvc-3-part-2)。但它並不十分清楚你想做什麼。如果您希望在PhoneNumber上具有Required驗證屬性,該屬性也確保AreaCode具有值,那麼您應該只將一個屬性應用於PhoneNumber,並且該屬性接受其他屬性的NAE的參數。 –