locked
Validation message won't go away RRS feed

  • Question

  • User657329123 posted

    Hi there,

    I have a form with all except one required fields. Validation is working fine for all fields in the form except the radiobutton group. If a form is submitted without filling anything, I see error message beside each field saying that it is a required field. This message goes away as soon as I enter something in that field and switch focus to the next field.

    I have only one radio button group in the form. If nothing is selected from this group and form is submitted, red error message is displayed as it should. When a radio button is selected from this group, the error message should go away but it is not going away.

    Here is my code for radio button:

            <div class="form-group">
                @Html.LabelFor(model => model.Equipment, string.Format("{0} *", Html.DisplayNameFor(model => model.Equipment)), htmlAttributes: new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    <span>Desktop </span> @Html.RadioButtonFor(model => model.Equipment, "Desktop", htmlAttributes: new { @onchange = "makeReadonly();" })
                    <span> | Laptop </span>@Html.RadioButtonFor(model => model.Equipment, "Laptop", htmlAttributes: new { @onchange = "makeReadonly();" })
                    <span> | Other </span>@Html.RadioButtonFor(model => model.Equipment, "Other", htmlAttributes: new { @onchange = "makeWritable();" })
                    @Html.ValidationMessageFor(model => model.Equipment, "", new { @class = "text-danger" })
                </div>
            </div>

    <div class="form-group">
    @Html.LabelFor(model => model.OtherEquipment, htmlAttributes: new { @class = "control-label col-md-2" })
    <div class="col-md-10">
    @Html.EditorFor(model => model.OtherEquipment, new { htmlAttributes = new { @class = "form-control", @readonly = "readonly" } })
    @Html.ValidationMessageFor(model => model.OtherEquipment, "", new { @class = "text-danger" })
    </div>
    </div>

    Then at the bottom of the page I have the following:

    @section Scripts {
        @Scripts.Render("~/bundles/jquery")
        @Scripts.Render("~/bundles/jqueryval")
        @Scripts.Render("~/bundles/jqueryui")
        @Scripts.Render("~/bundles/modernizr")
        @Scripts.Render("~/bundles/bootstrap")
    
        <script type="text/javascript">
    
            function makeWritable() {
                $("#OtherEquipment").prop('readonly', false);
                $("#OtherEquipment").val("");
            }
    
            function makeReadonly() {
                $("#OtherEquipment").prop('readonly', true);
                $("#OtherEquipment").val("");
            }
    
    }

    There are no JavaScript error messages being thrown.

    Any idea why validation works fine for all fields except this radio button group?

    Joe

    Tuesday, September 10, 2019 5:48 PM

All replies

  • User-474980206 posted

    the radio button validation is done server side. so the error message will not be cleared until a post back. while jQuery validation supports radio button groups, MVC unobtrusive does not. but you can manually add the data-val attributes to one of the radio buttons, and it will register the whole group with jQuery validation:

                   <span>Desktop </span> @Html.RadioButtonFor(model => model.Equipment, "Desktop", htmlAttributes: new { @onchange = "makeReadonly();", data-val-required="Please choose equipment" })
     

    Wednesday, September 11, 2019 3:41 AM
  • User-17257777 posted

    Hi joegreen2005,

    I test with your codes, and everything works fine, this is my test demo:

    Model:

    public class User
        {
            [Required(ErrorMessage = "cant be null")]
            public string Username { get; set; }
    
            [Required(ErrorMessage = "cant be null")]
            public string Password { get; set; }
    
            [Required(ErrorMessage = "cant be null")]
            public string Equipment { get; set; }
    
            public string OtherEquipment { get; set; }
        }

    Controller:

            [HttpPost]
            [ValidateAntiForgeryToken]
            public ActionResult Index(User user)
            {
                if (ModelState.IsValid)
                {
                    return Content(user.Username+ " |" + user.Password+" |"+user.Equipment+" |"+user.OtherEquipment);
                }
                return View();
            }

    View:

    @using (Html.BeginForm())
    {
        @Html.AntiForgeryToken()
    
        <div class="form-horizontal">
            <h4>User</h4>
            <hr />
            @Html.ValidationSummary(true, "", new { @class = "text-danger" })
            <div class="form-group">
                @Html.LabelFor(model => model.Username, htmlAttributes: new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    @Html.EditorFor(model => model.Username, new { htmlAttributes = new { @class = "form-control" } })
                    @Html.ValidationMessageFor(model => model.Username, "", new { @class = "text-danger" })
                </div>
            </div>
    
            <div class="form-group">
                @Html.LabelFor(model => model.Password, htmlAttributes: new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    @Html.EditorFor(model => model.Password, new { htmlAttributes = new { @class = "form-control" } })
                    @Html.ValidationMessageFor(model => model.Password, "", new { @class = "text-danger" })
                </div>
            </div>
    
            <div class="form-group">
                @Html.LabelFor(model => model.Equipment, string.Format("{0} *", Html.DisplayNameFor(model => model.Equipment)), htmlAttributes: new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    <span>Desktop </span> @Html.RadioButtonFor(model => model.Equipment, "Desktop", htmlAttributes: new { @onchange = "makeReadonly();" })
                    <span> | Laptop </span>@Html.RadioButtonFor(model => model.Equipment, "Laptop", htmlAttributes: new { @onchange = "makeReadonly();" })
                    <span> | Other </span>@Html.RadioButtonFor(model => model.Equipment, "Other", htmlAttributes: new { @onchange = "makeWritable();" })
                    @Html.ValidationMessageFor(model => model.Equipment, "", new { @class = "text-danger" })
                </div>
            </div>
    
            <div class="form-group">
                @Html.LabelFor(model => model.OtherEquipment, htmlAttributes: new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    @Html.EditorFor(model => model.OtherEquipment, new { htmlAttributes = new { @class = "form-control", @readonly = "readonly" } })
                    @Html.ValidationMessageFor(model => model.OtherEquipment, "", new { @class = "text-danger" })
                </div>
            </div>
    
            <div class="form-group">
                <div class="col-md-offset-2 col-md-10">
                    <input type="submit" value="Create" class="btn btn-default" />
                </div>
            </div>
        </div>
    }
    
    @section Scripts {
        @Scripts.Render("~/bundles/jquery")
        @Scripts.Render("~/bundles/jqueryval")
        @Scripts.Render("~/bundles/jqueryui")
        @Scripts.Render("~/bundles/modernizr")
        @Scripts.Render("~/bundles/bootstrap")
    
        <script type="text/javascript">
    
            function makeWritable() {
                $("#OtherEquipment").prop('readonly', false);
                $("#OtherEquipment").val("");
            }
    
            function makeReadonly() {
                $("#OtherEquipment").prop('readonly', true);
                $("#OtherEquipment").val("");
            }
        </script>
    }

    Test Result:

    Have you included the jquery.validate in ~/bundles/jqueryval ?

    bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
                            "~/Scripts/jquery.validate*"));

    Best Regards,

    Jiadong Meng

    Wednesday, September 11, 2019 6:44 AM
  • User657329123 posted

    bruce is correct in that radio button validation is done server side because on post back validation error message goes away. 

    When I add data-val-required="Please choose equipment" attribute, I get a red wiggle line under it and error saying - CS0746: Invalid anonymous type member declarator. Anonymous type members must be declared with a member assignment, simple name or member access.

    jiadongm yes I do have following in BundleConfig.cs but I'm not sure why how it works for you but it doesn't for me.

    bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
                            "~/Scripts/jquery.validate*"));

    Wednesday, September 11, 2019 12:08 PM
  • User657329123 posted

    I found that  '-' gives the wiggle line but by replacing it underscore works. .Net converts _ to - and source code shows data-val-required. but still doesn't work.

    Wednesday, September 11, 2019 12:27 PM
  • User-474980206 posted

    you are correct. as "-" is not allowed in C# variable names, to use a "-" in an html attribute you use "_", which is translated to "-" on render. 

    if you manually set data-val attributes you must also enable validation. add:

      data-val="true"

    so you have to enable the validation, and define the rules.

       <input data-val="true" data-val-required="required message" />

    Wednesday, September 11, 2019 4:34 PM
  • User657329123 posted

    I've added the following all three radio buttons in a group.

    data_val="true", data_val_required="required message"

    In web.config I have

        <add key="ClientValidationEnabled" value="true" />
        <add key="UnobtrusiveJavaScriptEnabled" value="true" />

    I have removed data annotation [Required] from model. Still not working. What am I missing to make this work?

    Wednesday, September 11, 2019 5:02 PM
  • User-17257777 posted

    Hi joegreen2005,

    I've added the following all three radio buttons in a group.

    data_val="true", data_val_required="required message"

    In web.config I have

        <add key="ClientValidationEnabled" value="true" />
        <add key="UnobtrusiveJavaScriptEnabled" value="true" />

    I have removed data annotation [Required] from model. Still not working. What am I missing to make this work?

    Could you please elaborate on what is “ still not working”? I tried your code within your last post, it works pretty fine for me.

    1. Did you get any errors in Console?
    2. Also, is the form field submitted with a correct name?
    3. Finally, if you still cannot make it, could you please show us the related codes, including the complete cshtml/ model/ controller action and the scripts you have added.

    Best Regards,

    Jiadong Meng

    Tuesday, September 24, 2019 7:09 AM