locked
Custom validation for checkboxes RRS feed

  • Question

  • User968462096 posted

    Hi Guys

    I have a form with a group of 9 checkboxes.  I want to validate that at least 1 and maxium of 3 are checked. 

    I'm assuming the logic is going to be to give them all the same name and then check the length of the array after split().  Question is though how do I link up this custom validation?

    Thanks

    David

    Wednesday, February 24, 2016 8:35 PM

All replies

  • User1633621018 posted

    Hi David,

    You can try below sample:

    var checkboxes = $("input[type='checkbox']"),
        submitButt = $("input[type='button']");
    
    submitButt.click(function() {
        var count= parseInt($(":checkbox:checked").length);
        if(count==0 || count >3)
        {
        alert('error');
        }
    });
    
    
    <h1>Button should be enabled if at least one checkbox is checked</h1>
    
    <form>
        <div>
            <input type="checkbox" name="option-1" id="option-1"> <label for="option-1">Option 1</label>
        </div>
        <div>
            <input type="checkbox" name="option-2" id="option-2"> <label for="option-2">Option 2</label>
        </div>
        <div>
            <input type="checkbox" name="option-3" id="option-3"> <label for="option-3">Option 3</label>
        </div>
        <div>
            <input type="checkbox" name="option-4" id="option-4"> <label for="option-4">Option 4</label>
        </div>
        <div>
            <input type="checkbox" name="option-5" id="option-5"> <label for="option-5">Option 5</label>
        </div>
        
        <div>
            <input type="button" value="Do thing" >
        </div>
    </form>
    

    You can try at fiffle:http://jsfiddle.net/chriscoyier/bphze/76/

    Wednesday, February 24, 2016 8:56 PM
  • User2103319870 posted

    I have a form with a group of 9 checkboxes.  I want to validate that at least 1 and maxium of 3 are checked. 

    You can also try with the below code

    <!DOCTYPE html>
    <html>
    <head>
    <script src="https://code.jquery.com/jquery-1.11.3.js"></script>
    <script>
    $(document).ready(function () {
                    //Attach click event to button
                    $("#Button1").click(function () {
                        //Set the max and min allowed values here
                        var maxAllowed = 3;
                        var minAllowed = 1;
                        //Get the total number of checkboxes checked
                        var cnt = $("input[name='Group1']:checked").length;
                        //Check if selected count is greater than max allowed count
                        if (cnt > maxAllowed) {
                            //If so uncheck the checkbox
                            $(this).prop("checked", "");
                            //Show the message
                            alert('You can Select maximum ' + maxAllowed + ' checkboxes');
                        }
                        //Check if selected count is greater than min allowed count
                        if (cnt < minAllowed) {
                            //If so show the message
                            alert('Please select atleast one');
                        }
                    });
                });
    </script>
    </head>
    <body>
    
            <input name='Group1' type='checkbox' value='1' />
            <input name='Group1' type='checkbox' value='2' />
            <input name='Group1' type='checkbox' value='3' />
            <input name='Group1' type='checkbox' value='4' />
            <input name='Group1' type='checkbox' value='5' />
            <input name='Group1' type='checkbox' value='6' />
            <input name='Group1' type='checkbox' value='7' />
            <input name='Group1' type='checkbox' value='8' />
            <input name='Group1' type='checkbox' value='9' />
            <input id="Button1" type="button" value="button" />
    </body>
    </html>
    Wednesday, February 24, 2016 9:17 PM
  • User968462096 posted

    Thanks.

    I was thinking more of the server side version though in razor.  I'll use the jquery versions too but I also need a c# way of doing it.

    Wednesday, February 24, 2016 9:34 PM
  • User-2057865890 posted

    Hi David,

    If you want to validate on server side, you could try following.

    if (!string.IsNullOrEmpty(Request["checkList"]))
    {
         var count = Request["checkList"].Split(',').Count();
         if (count > 3)
         {
             //select maximum 3 items
         }
    }
    else
    {
         // select at least one item
    }

    Best Regards,

    Chris Zhao

    Thursday, February 25, 2016 9:33 AM
  • User968462096 posted

    Thanks Chris, I've done something very similar with a custom validator based on Mike's article here

    http://www.mikesdotnetting.com/article/195/asp-net-web-pages-creating-custom-validators

    Now I am wondering if there is a way to pass back a different error message based on the code below:

    public MyCheck(string errorMessage = null) : base(errorMessage){}
    
    protected override bool IsValid(HttpContextBase httpContext, string value)
    {
        if (!String.IsNullOrEmpty(value))
        {
            var results = value.Split(',');
            return results.Length <= 3;
            //error is max 3 to be checked
        }
        return false;
        //error is min 1 checked
    }

    Thursday, February 25, 2016 10:36 AM