开发者

Asp.Net MVC validation annotation regular expression attribute

When I have a checkbox in my form it is not enough to mark the matching property as Required because a true or false is sent as it's value.

Whats the best way to validate this in the model? I was thinking a regular expression to match the string true but I am either not writing it correctly or it does not work on a Boolean property.

public bool FeeAgree
    {
        get
        {
            return _feeAgree;
        }
        set
        {
            _feeAgree = value;
        }
    }

Above is the property I am trying to validate. Using the Required attribute does not work because the Html.CheckBoxFor creates a hidden f开发者_开发问答ield so there is always a valueof either true or false passed.


You don't need any data annotation for boolean properties. If the value is not true or false the default model binder will handle the case when trying to parse it and add a model error. So basically just by the fact of having such model property it would only accept true or false. Every other value would be considered as error.

If you were using a nullable boolean you could enforce it to have a value with the Required attribute:

[Required]
public bool? FeeAgree { get; set; }

To ensure that the user checked the checkbox you could write a custom validation attribute:

public class MustBeTrueAttribute : ValidationAttribute
{
    public override bool IsValid(object value)
    {
        return value != null && (bool)value;
    }
}

and then:

[MustBeTrue(ErrorMessage = "You must accept the terms and conditions")]
public bool FeeAgree { get; set; }


This solution could be extended to include client side validation.

public class MustBeTrueAttribute : ValidationAttribute, IClientValidatable {

    public override bool IsValid(object value) {
        return value is bool && (bool)value;
    }

    public IEnumerable<ModelClientValidationRule> GetClientValidationRules(
        ModelMetadata metadata, ControllerContext context) {

        return new ModelClientValidationRule[] {
        new ModelClientValidationRule {
            ValidationType = "checkboxtrue",
            ErrorMessage = this.ErrorMessage
        }};
    }
}

Then if the view included a bit of jquery code to add the "checkboxtrue" validation type...

jQuery.validator.unobtrusive.adapters.add("checkboxtrue", function (options) {
    if (options.element.tagName.toUpperCase() == "INPUT" && options.element.type.toUpperCase() == "CHECKBOX") {
        options.rules["required"] = true;
        if (options.message) {
            options.messages["required"] = options.message;
        }
    }
});

The result is client-side checkbox validation

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜