さて、私はそれが私が望んでいた/想像したよりも少し多くの仕事でしたが、私が望む結果を得る方法を見つけました。私が見逃していたのは、カスタム検証クラスでIClientValidatableを実装せず、カスタム検証を試したjQuery Validator addmethodに追加する必要があったが、カスタム検証クラスでIClientValidatableを実装しなかったため、すぐに実行します。すべてのjQueryのものがセットアップ/含まれていると仮定してこれを機能させる方法
まず、カスタム検証属性を使用する単純なモデルを作成します
public class Person
{
[Required]
[Display( Name="Name")]
public string Name { get; set; }
public int Age { get; set; }
//Uses a custom data annotation that requires that at lease it self or the property name passed in the constructor are not empty
[OneOfTwoRequired("Mobile")]
public string Phone { get; set; }
[OneOfTwoRequired("Phone")]
public string Mobile { get; set; }
}
リフレクションを使用して、テストに渡される文字列名のプロパティを取得するカスタム検証クラス
2012年8月15日現在:MVC 4を使用している場合、ModelClientValidationRuleはMVC 4に存在しないようであるため、IClientValidatableを使用するにはSystem.web.mvc3.0を参照する必要があります。
public class OneOfTwoRequired : ValidationAttribute, IClientValidatable
{
private const string defaultErrorMessage = "{0} or {1} is required.";
private string otherProperty;
public OneOfTwoRequired(string otherProperty)
: base(defaultErrorMessage)
{
if (string.IsNullOrEmpty(otherProperty))
{
throw new ArgumentNullException("otherProperty");
}
this.otherProperty = otherProperty;
}
public override string FormatErrorMessage(string name)
{
return string.Format(ErrorMessageString, name, otherProperty);
}
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
PropertyInfo otherPropertyInfo = validationContext.ObjectInstance.GetType().GetProperty(otherProperty);
if (otherPropertyInfo == null)
{
return new ValidationResult(string.Format("Property '{0}' is undefined.", otherProperty));
}
var otherPropertyValue = otherPropertyInfo.GetValue(validationContext.ObjectInstance, null);
if (otherPropertyValue == null && value == null)
{
return new ValidationResult(this.FormatErrorMessage(validationContext.DisplayName));
}
return ValidationResult.Success;
}
public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
yield return new ModelClientValidationRule
{
ErrorMessage = FormatErrorMessage(metadata.DisplayName),
//This is the name of the method aaded to the jQuery validator method (must be lower case)
ValidationType = "oneoftworequired"
};
}
}
これをビューまたは部分ビューに追加します。これが$(document).readyメソッドに含まれていないことを確認する必要があります
jQuery.validator.addMethod("oneoftworequired", function (value, element, param) {
if ($('#Phone).val() == '' && $('#Mobile).val() == '')
return false;
else
return true;
});
jQuery.validator.unobtrusive.adapters.addBool("oneoftworequired");
jQueryバリデーターは、ポストバックせずに、または最初のページの読み込み時にフォームを検証する場合にのみ必要と思われます。そのためには、$('form')。valid()を呼び出すだけです。
これが誰かに役立つことを願っています:)