Search code examples
c#.netasp.net-core-mvc

Make checkbox required with Data Annotations


I want to show message for the user that he must accepted the terms after he submit the form if the checkbox is unchecked and submit the form if the checkbox is checked.

I have this code on my model:

public class UserClass
{
    [Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    [Required(ErrorMessage = "Entry ID")]
    public int ID { get; set; }
    [Required(ErrorMessage = "Entry Name")]
    public string Name { get; set; }
}

Controller:

private readonly ApplicationUserClass _auc;
public abcController(ApplicationUserClass auc)
{
    _auc = auc;
}

public IActionResult Index()
{
    return View();
}

public IActionResult Create()
{
    return View();
}

[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult Create(UserClass uc)
{
    _auc.Add(uc);
    _auc.SaveChanges();
    return View();
}

View:

<div class="row">
    <div class="col-md-9">
        <form asp-action="Create">
            <div asp-validation-summary="ModelOnly" class="text-danger"></div>
            <div class="form-group">
                <label asp-for="ID" class="control-label"></label>
                <input asp-for="ID" class="form-control" />
                <span asp-validation-for="ID" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="Name" class="control-label"></label>
                <input asp-for="Name" class="form-control" />
                <span asp-validation-for="Name" class="text-danger"></span>
            </div>

            <div class="form-group">
                <div class="col-md-offset-2 col-md-10">
                    <input type="submit" value="sumbit" class="btn btn-primary" />
                </div>
            </div>
            <b>@ViewBag.message</b>
        </form>
    </div>
</div>

I see a lot of examples, but not work. Anybody can give advise?


Solution

  • You could refer to the following sample:

    1. Create a UserViewModel to transfer data between View and controller:

       public class UserViewModel
       {
           [Required(ErrorMessage = "Entry ID")]
           public int ID { get; set; }
           [Required(ErrorMessage = "Entry Name")]
           public string Name { get; set; } 
           //use custom validation method
           [CheckBoxRequired(ErrorMessage ="Please checked the items")]
           public bool IsAccepted { get; set; } 
       }
      
    2. Add the custom validation method:

       public class CheckBoxRequired : ValidationAttribute
       {
           protected override ValidationResult IsValid(object value, ValidationContext validationContext)
           {
               //get the entered value
               var student = (UserViewModel)validationContext.ObjectInstance;
               //Check whether the IsAccepted is selected or not.
               if (student.IsAccepted == false)
               { 
                   //if not checked the checkbox, return the error message.
                   return new ValidationResult(ErrorMessage == null ? "Please checked the checkbox" : ErrorMessage); 
               }
               return  ValidationResult.Success;
           }
       }
      
    3. Create the Action methods to create user and use the UserViewModel to transfer data between View and Controller.

           public IActionResult CreateUser()
           {
               return View();
           }
           [HttpPost]
           public IActionResult CreateUser(UserViewModel user)
           {
               if (ModelState.IsValid)
               {
                  //after validation success, create a UserClass instance based on the ViewModel, and insert the "newuser" into database.
                   var newuser = new UserClass();
                   newuser.ID = user.ID;
                   newuser.Name = user.Name;       
                   //save the newuser into the database via dbcontext
                   _dbcontext.UserClass.Add(newuser);
                   _dbcontext.SaveChanges();
                   return RedirectToAction(nameof(Index));
               }
               return View();
           }
      
    4. Create a CreateUser View page:

           @model WebApplication2.Models.UserViewModel
      
           @{
               ViewData["Title"] = "CreateUser";
               Layout = "~/Views/Shared/_Layout.cshtml";
           } 
           <div class="row">
               <div class="col-md-6">
                   <form asp-action="CreateUser">
                       <div asp-validation-summary="ModelOnly" class="text-danger"></div>
                       <div class="form-group">
                           <label asp-for="ID" class="control-label"></label>
                           <input asp-for="ID" class="form-control" />
                           <span asp-validation-for="ID" class="text-danger"></span>
                       </div>
                       <div class="form-group">
                           <label asp-for="Name" class="control-label"></label>
                           <input asp-for="Name" class="form-control" />
                           <span asp-validation-for="Name" class="text-danger"></span>
                       </div>
                       <div class="form-group form-check">
                           <label class="form-check-label">
                               <input class="form-check-input" asp-for="IsAccepted" /> @Html.DisplayNameFor(model => model.IsAccepted)
      
                           </label>
                           <span asp-validation-for="IsAccepted" class="text-danger"></span>
                       </div> 
                       <div class="form-group">
                           <input type="submit" value="Create" class="btn btn-primary" />
                       </div>
                   </form>
               </div>
           </div> 
      
           @section Scripts {
               @{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
           }
      

    Then, the screenshot as below:

    enter image description here