だから私は望んでいたよりも少し仕事があったと思っていましたが、結果を得る方法を見つけました。 私が見落としていたものは、私のカスタム検証クラスにIClientValidatableを暗示していなかったし、jlery 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; }
}
プロパティを取得するためにリフレクションを使用してカスタム検証クラステストに渡された文字列名のうち
/08/2012のよう
注:あなたがMVC 4を使用している場合ModelClientValidationRuleは何が
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"
};
}
}
MVC 4に存在するように見えるしませんよう、あなたはIClientValidatableの使用System.web.mvc 3.0を参照のする必要があります。
これをビューまたはパーシャルビューに追加するには、これが$(ドキュメント)にないことを確認する必要があります。あなたが戻って掲示することなく、または最初のページの読み込み時にフォームを検証するために、あなただけの($を呼び出すことを行いたい場合は準備の方法は
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のバリのもののみを必要としているようですこれは誰かに役立ちます「形式」)。有効()
希望:)
errはいもっと一般的なスクリプトを使うことができましたが、これは1ページあたり1つの携帯電話1つの要素しか持たないケースだったので、一般的ですが、if($( '。 val()== '' && $( '。Option2')。val()== '')、それはもっと一般的なものになります。 – Troublesum