How to add boolean required attribute in mvc?

Sonu K picture Sonu K · Sep 30, 2014 · Viewed 27.5k times · Source

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?

Answer

Sonu K picture Sonu K · Sep 30, 2014
[Display(Name = "Is Active")]
[Range(typeof(bool), "true", "true", ErrorMessage="The field Is Active must be checked.")]
public bool IsActive { get; set; }