Search code examples
asp.net-mvcforms-authenticationclient-side-validation

mvc client side validation with required attribute not working


i am using bootstrap multiselect plugin

            <select class="btn btn-default  col-md-1" name="fw_dropdown" id="fw_dropdown" multiple="multiple" required="required">
            @foreach (var fw in Model.FWIndex)
            {
                <option value="@fw">@fw</option>
            }
        </select>

after I add the required attribute, the form is able to display a message that the field is not selected. However, when I proceed to select the field, the message kept showing, which seems that the selected value cannot be received. When I reload the project and select the required field, I am able to proceed with the submit query.

How do I fix this?


Solution

  • Seems that the required attribute only works for select class in IE when multiple selection is not enabled (I'm using bootstrap multiselect).

    Instead I write a function in the submit button to achieve validation.

    <script>
            $(document).ready(function(event){
                $("form").submit(function(event){
                    var fw=$("#fw_dropdown").val();
                    if(fw=="" || fw==null){
                        alert("Please select FW!");
                        //prevent form submission
                        event.preventDefault();
                    }
                    //allow form submission only when if is not true
                });
            })
    </script>
    

    To generate the form in the web application I used the html helper.

    @using (Html.BeginForm("Query", "Actuals"))
    

    That's why "form" is used instead of form id