пятница, 24 августа 2012 г.

MVC Model require True


You could create your own validator:
public class IsTrueAttribute : ValidationAttribute
{
    #region Overrides of ValidationAttribute

    /// 
    /// Determines whether the specified value of the object is valid. 
    /// 

   
///
   
/// true if the specified value is valid; otherwise, false.
   
///
   
/// The value of the specified validation object on which the is declared.
   
///                
   
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;
   
}

   
#endregion
}


You could either create your own attribute or use the CustomValidationAttribute.
This is how you would use the CustomValidationAttribute:
[CustomValidation(typeof(BoolValidation), "ValidateBool")]
where BoolValidation is defined as:
public class BoolValidation
{
  public static ValidationResult ValidateBool(bool boolToBeTrue)
  {
    if (boolToBeTrue)
    {
      return ValidationResult.Success;
    }
    else
    {
      return new ValidationResult(
          "Bool must be true.");
    }
  }


You culd create a validator for both Server AND Client side. Using MVC and unobtrusive form validation, this can be achieved simply by doing the following:
Firstly, create a class in your project to perform the server side validation like so:
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"
        };
    }
}
Following this, annotate the appropriate property in your model:
[EnforceTrue(ErrorMessage=@"Error Message")]
public bool ThisMustBeTrue{ get; set; }
And Finally, enable client side validation by adding the following script to your View:
<script type="text/javascript">
    jQuery.validator.addMethod("enforcetrue", function (value, element, param) {
        return element.checked;
    });
    jQuery.validator.unobtrusive.adapters.addBool("enforcetrue");
</script>
Note: We already created a method GetClientValidationRules which pushes our annotation to the view from our model.




Комментариев нет: