validate checkbox group

2 posts, 0 answers
  1. George
    George avatar
    18 posts
    Member since:
    Jul 2019

    Posted 26 Sep 2019 Link to this post

    I have a checkbox group and only want to make sure what is checked if required.It's validating all checkboxes, I only to validate the group is required.

    this creates textboxes on the page, and it can be 1 or many, however, if x.Required is true, I only want to validate the group not each checkbox. Is that possible with the validator or no, if not, can I remove the checkboxes from the validator since they have an input tag with textboxes?

    foreach(var x in group)
    {
           <input type="checkbox" name="@x.Location" value="@x.Text" required="@x.Required"/>
    }
  2. Veselin Tsvetanov
    Admin
    Veselin Tsvetanov avatar
    1231 posts

    Posted 30 Sep 2019 Link to this post

    Hello George,

    In order to achieve the desired, I would suggest you define a custom validation rule for the Kendo validator. That could be configured in the following way:

    <form id="form">
    	@{
    		var group = Model as IEnumerable<ValidationCheckbox.Models.TestViewModel>;
    
    		foreach (var x in group)
    		{
    			<input type="checkbox" name="@x.Location" value="@x.Text" data-required="@x.Required"  />
    		}
    	}
    
    	<input type="submit"/>
    	</form>
    <script>
    	$("#form").kendoValidator({
    		rules: {
    			validateCheckboxes: function (input) {
    				if (input.attr("data-required") === "True") {
    					var allCheckboxes = $('#form').find('input[data-required="True"]');
    					var valid = false;
    
    					allCheckboxes.each(function () {
    						console.log($(this).is(":checked"))
    						if ($(this).is(":checked")) {
    							valid = true;
    						}
    					});
    
    					return valid;
    				}
    
    				return true;
    			}
    		}
    	});
    
    	$("form").submit(function (event) {
    		var validator = $("#form").getKendoValidator();
    
    		if (validator.validate()) {
    			alert("Hooray! Your tickets has been booked!");
    		} else {
    			event.preventDefault();
    		}
    	});
    </script>

    Attached you will find a sample project implementing the above.

    Regards,
    Veselin Tsvetanov
    Progress Telerik

    Get quickly onboarded and successful with your Telerik and/or Kendo UI products with the Virtual Classroom free technical training, available to all active customers. Learn More.
Back to Top