Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add boolean required attribute in mvc?

I have one model class like:

public class Student {     [DataType(DataType.Date)]     [DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]     [Display(Name = "Enrollment Date")]     public DateTime EnrollmentDate { get; set; }      [Required]     [Display(Name = "Is Active")]     public bool IsActive { get; set; }      public virtual ICollection<Enrollment> Enrollments { get; set; } } 

Here I have created a Boolean property IsActive with Required attribute, but the problem is that my view is not executing the required validation for this property? I want to bind this property with a CheckBox and check if this CheckBox is checked and run validation if it is not.

Any solution for this?

like image 636
Sonu K Avatar asked Sep 30 '14 13:09

Sonu K


People also ask

What does the required attribute of a Boolean mean in JavaScript?

The Required attribute just means that the property has to have a value. In the case of boolean (checkbox) the value false (or unchecked) is still a valid answer. I knew this fact that it is not working because unchecked is also a valid value for Boolean property, that's why I am looking for a solution to this.

What is required attribute in ASP NET MVC?

Required Attribute in ASP.NET MVC: let’s understand Required Attribute with one example. Our business requirement is that the First name and Last Name of an employee can’t be empty. That means we will force the Employee to give the first name and last name; we can achieve this very easily in ASP.NET MVC application by decorating the ...

How to create a model class in MVC?

Let’s create the Model class as follows, Once creating the new MVC Project Solution, right-click on the Model folder and add a new class Addà Class as shown below, Once adding the new class, give the proper name to the Model and click add. To create the model, this corresponds to the database table,

What are the built-in data annotation attributes available in MVC?

So let’s discuss the built-in Data Annotation Attributes that are available in ASP.NET MVC for model validation one by one. Note: Data annotations are the attributes that we can find in the System.ComponentModel.DataAnnotations namespace. These attributes provide Server-side validation as well as client-side validation.


1 Answers

[Display(Name = "Is Active")] [Range(typeof(bool), "true", "true", ErrorMessage="The field Is Active must be checked.")] public bool IsActive { get; set; } 
like image 135
Sonu K Avatar answered Sep 28 '22 07:09

Sonu K