This is a migrated thread and some comments may be shown as answers.

validate checkbox group

1 Answer 818 Views
Validation
This is a migrated thread and some comments may be shown as answers.
George
Top achievements
Rank 1
George asked on 26 Sep 2019, 12:20 PM

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"/>
}

1 Answer, 1 is accepted

Sort by
0
Veselin Tsvetanov
Telerik team
answered on 30 Sep 2019, 10:02 AM

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.
Tags
Validation
Asked by
George
Top achievements
Rank 1
Answers by
Veselin Tsvetanov
Telerik team
Share this question
or