0

when running the page the validation on range brings up the required error but ignores the true true and false false it returns an error message when the check box is ticked regardless of what the range is set to. for example when the range is set to true true and the check box is ticked it gives me an error message and when it is not ticked it allows me to continue with no error. when range is false false it acts exactly the same.

it should error when not ticked

<p>
Please confirm you have read the <a href="~/Downloads/AccreditationAndSTCompanyEligibility.pdf" target="_blank">eligibility document.</a>
 @Html.CheckBoxFor(m => m.ConfirmEligibilityDocument)
@Html.ValidationMessageFor(m => m.ConfirmEligibilityDocument)

</p>

[Range(typeof(bool), "true", "true", ErrorMessage = "You must accept our Terms & Conditions.")]
public bool ConfirmEligibilityDocument { get; set; }
ekad
  • 14,436
  • 26
  • 44
  • 46
Moffatt
  • 39
  • 4

1 Answers1

0

please try to replace your range attribute with

[MustBeTrue(ErrorMessage = "You must accept our Terms & Conditions")]

you will need the custom attribute for that

[AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = false)]
public class MustBeTrueAttribute : ValidationAttribute
{
  public override bool IsValid(object value)
  {
    return value != null && value is bool && (bool)value;
  }
}

This solution provided in this article

I don't know how your ptoject is setup, but here is my test code and it is works perfect

--Index.chtml

 @using (Html.BeginForm())

{ @Html.ValidationSummary(true)

   <p>please confirm that you have...</p>
  @Html.CheckBoxFor(m => m.ConfirmEligibilityDocument)
  @Html.ValidationMessageFor(m => m.ConfirmEligibilityDocument)

  <input type="submit" value="submit"/>

}

--HomeController.cs

 public class HomeController : Controller
{

    [HttpGet]
    public ActionResult Index()
    {
        ViewBag.Message = "Modify this template to jump-start your ASP.NET MVC application.";

        var t = new TestBool();


       return View();
    }

    [HttpPost]
    public ActionResult Index(TestBool t)
    {

        return View("Index",t);
    }


}

--TestBoll.cs - this is my model

 public class TestBool
{

    [MustBeTrue(ErrorMessage = "Must be accepted")]
    public bool ConfirmEligibilityDocument { get; set; }
}

--MustBeTrueAttribute.cs - this is attribute class

 [AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = false)]
public class MustBeTrueAttribute : ValidationAttribute
{
    public override bool IsValid(object value)
    {
        return value != null && value is bool && (bool)value;
    }
}
Community
  • 1
  • 1
Yuri
  • 2,820
  • 4
  • 28
  • 40
  • i have tried something similar already with no joy. i have just used your code and it has no affect at all :( – Moffatt Jun 04 '15 at 08:30