Imporre il valore booleano di un modello in modo che sia vero utilizzando le annotazioni dei dati

Imporre il valore booleano di un modello in modo che sia vero utilizzando le annotazioni dei dati
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Threading.Tasks;
using System.Web.Mvc;

namespace Checked.Entitites
{
    public class BooleanRequiredAttribute : ValidationAttribute, IClientValidatable
    {
        public override bool IsValid(object value)
        {
            return value != null && (bool)value == true;
        }

        public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
        {
            //return new ModelClientValidationRule[] { new ModelClientValidationRule() { ValidationType = "booleanrequired", ErrorMessage = this.ErrorMessage } };
            yield return new ModelClientValidationRule() 
            { 
                ValidationType = "booleanrequired", 
                ErrorMessage = this.ErrorMessageString 
            };
        }
    }
}

Puoi scrivere un attributo di convalida personalizzato che è già stato menzionato. Dovrai scrivere javascript personalizzato per abilitare la funzionalità di convalida discreta per raccoglierlo se stai eseguendo la convalida lato client. per esempio. se stai usando jQuery:

// extend jquery unobtrusive validation
(function ($) {

  // add the validator for the boolean attribute
  $.validator.addMethod(
    "booleanrequired",
    function (value, element, params) {

      // value: the value entered into the input
      // element: the element being validated
      // params: the parameters specified in the unobtrusive adapter

      // do your validation here an return true or false

    });

  // you then need to hook the custom validation attribute into the MS unobtrusive validators
  $.validator.unobtrusive.adapters.add(
    "booleanrequired", // adapter name
    ["booleanrequired"], // the names for the properties on the object that will be passed to the validator method
    function(options) {

      // set the properties for the validator method
      options.rules["booleanRequired"] = options.params;

      // set the message to output if validation fails
      options.messages["booleanRequired] = options.message;

    });

} (jQuery));

Un altro modo (che è un po' un trucco e non mi piace) è avere una proprietà sul tuo modello che sia sempre impostata su true, quindi utilizzare CompareAttribute per confrontare il valore dei tuoi *AgreeTerms * attributo. Semplice sì ma non mi piace :)


In realtà c'è un modo per farlo funzionare con DataAnnotations. Nel modo seguente:

    [Required]
    [Range(typeof(bool), "true", "true")]
    public bool AcceptTerms { get; set; }