开发者

How to require a checkbox to be checked at client side before form gets submitted to server in MVC 3?

开发者 https://www.devze.com 2023-03-14 13:18 出处:网络
I have a Terms and Condition checkbox on my signup page. I want to make it required like my few other fields on the form before posting to server.

I have a Terms and Condition checkbox on my signup page. I want to make it required like my few other fields on the form before posting to server. This validation must be done at client side.

Anyone knows how to do it properly?

I am using MVC 3, jquery.validate.min.js and jquery.validate.unobtrusive.min.js

Model:

[Required(ErrorMessage = "terms and condition")]
[Display(Name = "terms")]
public bool Terms { get; set; }

View:开发者_JAVA技巧

@Html.CheckBoxFor(m => m.Terms, new { @class = "cb" }) Terms & Condition
<button type="submit" id="btnSubmit" class="btn">Signup</button>

Also, Is it possible to call/trap some JS function when the submit button is clicked? That way I can easily use jquery to do validation and then submit?

Thanks for reading


You could write a custom validation attribute:

public class MustBeTrueAttribute : ValidationAttribute, IClientValidatable
{
    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        if (value is bool && (bool)value)
        {
            return ValidationResult.Success;
        }
        return new ValidationResult(String.Format(ErrorMessageString, validationContext.DisplayName));
    }

    public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
    {
        var rule = new ModelClientValidationRule
        {
            ErrorMessage = FormatErrorMessage(metadata.GetDisplayName()),
            ValidationType = "shouldbetrue"
        };

        yield return rule;
    }
}

which would be used to decorate your model:

[MustBeTrue(ErrorMessage = "terms and condition")]
[Display(Name = "terms")]
public bool Terms { get; set; }

and finally in the view register it:

@model MyViewModel

@using (Html.BeginForm())
{
    @Html.CheckBoxFor(m => m.Terms, new { @class = "cb" }) 
    <text>Terms &amp; Condition</text>
    @Html.ValidationMessageFor(x => x.Terms)

    <button type="submit" id="btnSubmit" class="btn">Signup</button>
}

<script src="@Url.Content("~/Scripts/jquery.validate.js")" type="text/javascript"></script>           
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.js")" type="text/javascript"></script>           

<script type="text/javascript">
    jQuery.validator.addMethod('shouldbetruemethod', function (value, element) {
        return $(element).is(':checked');
    }, '');

    jQuery.validator.unobtrusive.adapters.addBool('shouldbetrue', 'shouldbetruemethod');
</script>


I would drop Terms from your model and simply add a checkbox to the page like so:

@using(Html.BeginForm()) {
...
<label>
    I agree to the terms & condition
    <input id="terms" type="checkbox" />
</label>
<button type="submit" id="btnSubmit" disabled="disabled" class="btn">Signup</button>
}

and attach an event handler to the change event to toggle your submit button.

$('#terms').change(function() {
    if($(this).is(':checked')) {
        $(this).siblings('button[type="submit"]').removeAttr('disabled');
    } else {
        $(this).siblings('button[type="submit"]').attr('disabled', 'disabled');
    }
});


Aren't you missing the validation part?

@Html.ValidationFor(m => m.Terms)

To hook up the submit is just hooking up, either the button click, or the form submit:

$(".btn").bind("click", function() {
    // Button was clicked, do stuff here
    return true; // so it can process the form submit
});

and

$("form").bind("submit", function() {
    // Form was submitted, do stuff here
    return true; // so it can process the form submit to the server (return false if you dont want to submit)
});

you can always use:

@using(Html.BeginForm("Action", "Controller", new { @id = "myForm" }, FormMethod.Post, null)) {
...
}

and hook up with the Selector Id

$("#myForm").bind("submit", function() { ... });

To use a CheckBox with the attribute Required, you need to do a custom validation just copy/paste Darin's code, to understand why the [Required] doesn't work out of the box you need to understand the output HTML

required validation in jQuery Validation means that a value is needed, like:

<input type="text" value="" id="myTextbox" />

but in case of a checkbox, a value is always there

<input type="checkbox" value="Yes" id="myChackbox" checked="checked" />

and

<input type="checkbox" value="Yes" id="myChackbox" />

so the Required is always true.

you just need to hook up a custom event, follow Darin's code and you set to go.

0

精彩评论

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