Checkbox validation (Razor Pages) RRS feed

  • Question

  • User1352447851 posted

    I am trying to create a required checkbox as part of my forum validation, however I cannot get tag helpers to work:


    <div class="form-group">
    <input type="checkbox" asp-for="MyModel.IsChecked" value="True">
    <label asp-for="MyModel.IsChecked" class="control-label">Click Here</label>
    <span asp-validation-for="MyModel.IsChecked" class="text-danger"></span>

    Model class:

    [RegularExpression(@"^True", ErrorMessage = "The checkbox is required")]
    public string IsChecked { get; set; }

    Monday, March 11, 2019 10:54 AM


  • User-893317190 posted

    Hi Shadow_Kittencorn,

    What is your model like?

    I have made a test. The value of checkbox will always be true not True, even if you write True it will be  changed into true.

    And your Regular expression only validates True not true, maybe this is the problem.

    Below is my code.

        public class MyModel
            [RegularExpression(@"^true", ErrorMessage = "The checkbox is required")]
            public string IsChecked { get; set; }

    My controller

            public IActionResult Index(MyModel myModel)
    myModel = myModel.IsChecked==null ? new MyModel() { IsChecked="True"}:myModel;
    return View(myModel);

    My razor.

    @model MyModel
        ViewData["Title"] = "Home Page";
    <form asp-controller="Home" asp-action="Index" class="form-horizontal" method="post">
        <input type="checkbox" asp-for="IsChecked" />
        <span asp-validation-for="IsChecked"
        <input type="submit" value="submit" />

    The result

    You could see the  check box's value is true not True.

    If this is not your case , please post your model.

    Best regards,

    Ackerly Xu

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Tuesday, March 12, 2019 2:20 AM