サーバー側とクライアント側の両方にバリデーターを作成します。MVC と目立たないフォーム検証を使用すると、次の手順を実行するだけでこれを実現できます。
まず、プロジェクトにクラスを作成して、次のようにサーバー側の検証を実行します。
public class EnforceTrueAttribute : ValidationAttribute, IClientValidatable
{
public override bool IsValid(object value)
{
if (value == null) return false;
if (value.GetType() != typeof(bool)) throw new InvalidOperationException("can only be used on boolean properties.");
return (bool)value == true;
}
public override string FormatErrorMessage(string name)
{
return "The " + name + " field must be checked in order to continue.";
}
public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
yield return new ModelClientValidationRule
{
ErrorMessage = String.IsNullOrEmpty(ErrorMessage) ? FormatErrorMessage(metadata.DisplayName) : ErrorMessage,
ValidationType = "enforcetrue"
};
}
}
これに続いて、モデルの適切なプロパティに注釈を付けます。
[EnforceTrue(ErrorMessage=@"Error Message")]
public bool ThisMustBeTrue{ get; set; }
最後に、次のスクリプトをビューに追加して、クライアント側の検証を有効にします。
<script type="text/javascript">
jQuery.validator.addMethod("enforcetrue", function (value, element, param) {
return element.checked;
});
jQuery.validator.unobtrusive.adapters.addBool("enforcetrue");
</script>
注:GetClientValidationRules
注釈をモデルからビューにプッシュするメソッドは既に作成しています。