Custom Validation for Checkbox in MVC Razor

Custom Validation for Checkbox in MVC Razor

04 Apr 2024
Intermediate
162K Views
3 min read

Checkboxes: An Overview

Checkboxes are used in a Razor Pages form to ensure users select zero or more predefined options. Checkboxes are nothing but a type of input element, and some aspects of their behavior are unique and need to be understood when deciding whether, and how to use them. In this MVC Tutorial, we will explore more about Custom Validation for Checkbox in MVC Razor. Consider our ASP.NET MVC Course for a better understanding of all MVC core concepts.

How to do it.

Follow the following steps to validate the checkbox in mvc razor.

Step 1: Making Custom Attribute

public class RegistrationModel { 
[Required(ErrorMessage = "Please Enter Email Address")] 
[RegularExpression(".+@.+\\..+", ErrorMessage = "Please Enter Correct Email Address")] 
public string UserName { get; set; }
[Required(ErrorMessage = "Please Enter Address")] 
[Display(Name = "Address")] 
public string Address { get; set; }
 // Applying Custom Attribute 
[MustBeTrue(ErrorMessage = "Please Accept the Terms & Conditions")] 
public bool TermsAccepted { get; set; } }
 //Making Custom attribute for validating checkbox 
// IClientValidatable for client side Validation
public class MustBeTrueAttribute : ValidationAttribute, IClientValidatable 
{ 
public override bool IsValid(object value) 
{ 
return value is bool && (bool)value; 
}
 // Implement IClientValidatable for client side Validation 
public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
 {
 return new ModelClientValidationRule[] {
 new ModelClientValidationRule { ValidationType = "checkboxtrue", ErrorMessage = this.ErrorMessage } };
 } 
} 

Step 2: Making Custom Validation using jQuery


 @model Mvc4_Model_ServerSideValidation.Models.RegistrationModel
@{ 
ViewBag.Title = "Validating CheckBox";
}
<script src="../../Scripts/jquery-1.7.1.min.js" type="text/javascript"></script>
<script src="../../Scripts/jquery.validate.min.js" type="text/javascript"></script>
<script src="../../Scripts/jquery.validate.unobtrusive.min.js" type="text/javascript"></script>
<script type="text/jscript">
 //Custom jQuery validation unobtrusive script and adapters 
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;
 }
 }
 }); </script>
<h2>Custom Validation for CheckBox </h2>
@using (Html.BeginForm())
{
 <fieldset> 
<legend>Custom Validation for Cascading Dropdown List</legend> 
<ol> 
<li> 
@Html.LabelFor(m => m.UserName) 
@Html.TextBoxFor(m => m.UserName, new { maxlength = 50 }) 
@Html.ValidationMessageFor(m => m.UserName) 
</li> 
<li> 
@Html.LabelFor(m => m.Address) 
@Html.TextAreaFor(m => m.Address, new { maxlength = 200 }) 
@Html.ValidationMessageFor(m => m.Address) 
</li> 
<li> 
@Html.CheckBoxFor(m => m.TermsAccepted)
@Html.ValidationMessageFor(m => m.TermsAccepted) 
</li> 
</ol> 
<input type="submit" value="Submit" /> 
</fieldset>
 }

How it works.

Now, you have applied the custom validation to the checkbox. This validation works for the client side and server side.

Conclusion
So in this article, we have learned about validating checkboxes in mvc3&4. I hope you enjoyed learning these concepts while programming with Asp.Net. Feel free to ask any questions from your side. Your valuable feedback or comments about this article are always welcome. Level up your career in MVC with our ASP.Net Core Certification.

FAQs

Q1. How do you write a validation for a checkbox?

The document. getElementById(); method can be used to select the checkbox in the DOM using the name specified in the id attribute in the input tag. 

Q2. How to check validation in checkbox?

Using checkbox_elemnt. checked attribute.

Q3. What is required validation in MVC checkbox?

The required attribute only validates whether a property has a value or not.
Share Article
Batches Schedule
About Author
Shailendra Chauhan (Microsoft MVP, Founder & CEO at Scholarhat by DotNetTricks)

Shailendra Chauhan is the Founder and CEO at ScholarHat by DotNetTricks which is a brand when it comes to e-Learning. He provides training and consultation over an array of technologies like Cloud, .NET, Angular, React, Node, Microservices, Containers and Mobile Apps development. He has been awarded Microsoft MVP 8th time in a row (2016-2023). He has changed many lives with his writings and unique training programs. He has a number of most sought-after books to his name which has helped job aspirants in cracking tough interviews with ease.
Self-paced Membership
  • 22+ Video Courses
  • 750+ Hands-On Labs
  • 300+ Quick Notes
  • 55+ Skill Tests
  • 45+ Interview Q&A Courses
  • 10+ Real-world Projects
  • Career Coaching Sessions
  • Email Support
Upto 60% OFF
Know More
Accept cookies & close this