2016-09-05 63 views
0

我以前使用這個鏈接實現多字段需要驗證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> 
    } 
+0

什麼不工作 - 客戶端或服務器端驗證或兩者兼而有之?您已經實現了'IClientValidatable',但沒有顯示腳本將規則添加到客戶端驗證所需的'$ .validator'中。 –

+0

服務器端和客戶端都不起作用。此外,我不知道我需要在javascript中執行的#.validator更改。 – Gaurav123

+0

要了解客戶端驗證需要什麼,請參閱[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的參數。 –

回答

1

您鏈接到答案和你根據它不會使一個很大的意義的代碼。在沒有包含關聯的@Html.ValidationMessageFor()的情況下將驗證屬性應用於AreaCode屬性毫無意義。

如果你想與PhoneNumber相關的驗證信息,將顯示一個請輸入一個電話號碼錯誤,如果它是空的,並顯示如果它不是空的一個也請輸入區號AreaCode值,那麼您需要一個僅應用於PhoneNumber屬性的屬性,並且該屬性需要接受另一個屬性名稱的參數。

型號

public string AreaCode { get; set; } 
[Required(ErrorMessage = "Please enter a phone number")] 
[RequiredWith("AreaCode", ErrorMessage = "Please also enter an Area Code")] 
public string PhoneNumber { get; set; } 

驗證屬性

[AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = true)] 
public class RequiredWithAttribute : ValidationAttribute, IClientValidatable 
{ 
    private const string _DefaultErrorMessage = "The {0} is also required."; 
    private readonly string _OtherPropertyName; 

    public RequiredWithAttribute(string otherPropertyName) 
    { 
     if (string.IsNullOrEmpty(otherPropertyName)) 
     { 
      throw new ArgumentNullException("otherPropertyName"); 
     } 
     _OtherPropertyName = otherPropertyName; 
     ErrorMessage = _DefaultErrorMessage; 
    } 

    protected override ValidationResult IsValid(object value, ValidationContext validationContext) 
    { 
     if (value != null) 
     { 
      var otherProperty = validationContext.ObjectInstance.GetType().GetProperty(_OtherPropertyName); 
      var otherPropertyValue = otherProperty.GetValue(validationContext.ObjectInstance, null); 
      if (otherPropertyValue == null) 
      { 
       return new ValidationResult(string.Format(ErrorMessageString, _OtherPropertyName)); 
      } 
     } 
     return ValidationResult.Success; 
    } 

    public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context) 
    { 
     var rule = new ModelClientValidationRule 
     { 
      ErrorMessage = FormatErrorMessage(_OtherPropertyName), 
      ValidationType = "requiredwith", 
     }; 
     rule.ValidationParameters.Add("dependentproperty", _OtherPropertyName); 
     yield return rule; 
    } 
} 

,並添加以下腳本

<script type="text/javascript"> 
    // General function to get the associated element 
    myValidation = { 
     getDependantProperyID: function (validationElement, dependantProperty) { 
      if (document.getElementById(dependantProperty)) { 
       return dependantProperty; 
      } 
      var name = validationElement.name; 
      var index = name.lastIndexOf(".") + 1; 
      dependantProperty = (name.substr(0, index) + dependantProperty).replace(/[\.\[\]]/g, "_"); 
      if (document.getElementById(dependantProperty)) { 
       return dependantProperty; 
      } 
      return null; 
     } 
    } 

    $.validator.addMethod("requiredwith", function (value, element, params) { 
     var dependantControl = $('#' + params.dependentproperty); 
     return dependantControl.val() !== ''; 
    }); 

    $.validator.unobtrusive.adapters.add("requiredwith", ["dependentproperty"], function (options) { 
     var element = options.element; 
     var dependentproperty = options.params.dependentproperty; 
     dependentproperty = myValidation.getDependantProperyID(element, dependentproperty); 
     options.rules['requiredwith'] = { 
      dependentproperty: dependentproperty 
     }; 
     options.messages['requiredwith'] = options.message; 
    }); 

</script> 
0

如果我不是錯MultiFieldRequ MVC3 Validating Multiple Fields As A Single Property

您也可以嘗試以下方法model.Also 添加命名空間

模型

:IRED上面 類名這是解釋在下面 計算器鏈接先前使用

=====================

using System.Web.Mvc; 

=====================

public class Customer 
    { 
     //...other fields here 
     [Remote("ValidateAreaPhoneNumber","Home",AdditionalFields="PhoneNumber",ErrorMessage="Please enter a phone number")] 

     public string AreaCode { get; set; } 

     public string PhoneNumber { get; set; } 
    } 

您可以寫信命名

ValidateAreaPhoneNumber

方法

in ur

主頁控制器

如下:

public JsonResult ValidateAreaPhoneNumber(string PhoneNumber) 
{ 

    //True:False--- action that implement to check PhoneNumber uniqueness 

     return false;//Always return false to display error message 
} 
相關問題