javascriptjqueryasp.net-mvcrazorunobtrusive-validation

jquery validate make one field required if another field is not empty


I'm having some issues with jQuery.validate 1.11 , with .Net 4.8 and MVC 5 with Razor.

I have these two properties in my class:

[StringLength(500, ErrorMessage = "{0} can have a max of {1} characters")]
public string MyProperty { get; set; }

[StringLength(100, ErrorMessage = "{0} can have a max of {1} characters")]
public string MyOtherProperty { get; set; }

And on my Razor page I have this:

@Html.TextBoxFor( m => m.MyProperty )
@Html.TextBoxFor( m => m.MyOtherProperty  )

@using (Html.BeginScripts()) {
    <script src="@Url.Content( "~/Scripts/MyScriptFile.js" )" type="text/javascript"></script>
    <script type="text/javascript">
        $(function () {
            MyScriptModule.Init();
        }); // end of document.ready
    </script>
}

And then my Javascript file is like this:

var $form = $("#MyForm");
var $submit = $("#Save");

var MyScriptModule = (function () {

    var init = function () {
    
    $submit.bind("click", function () {
        HandleSubmitLogic();
    });
    
    // Initialize form validation
        $form.validate({
            ignore: [],
            rules: {
                MyOtherProperty: {
                    required: function (element) {
                        return $("#MyProperty").val().length > 0;
                    }
                } 
            },
            errorPlacement: function (error, element) {
                error.appendTo(element.parent());
            },
        });

    }; // end init 
    
    function HandleSubmitLogic() {

        $submit.prop("disabled", true);
        ResetFormValidation($form);
        $form.validate();
        if ($form.valid()) {
            $form.submit();
        }
        $submit.prop("disabled", false);
    }
}

So the length validation fires as expected, but I can't get that rule to work, where MyOtherProperty is required IF MyProperty has a value. I got this from another StackOverflow link here, and it seems to fit with the online documentation here.

So what am I doing wrong?


Solution

  • Have the same issue when working in ASP.NET MVC.

    However, this can be solved by subscribing to the change event listener and adding/removing the required rule.

    // Initialize form validation
    $form.validate();
    
    $("#MyProperty").change(function () {
        if ($(this).val().length > 0) {
            $("#MyOtherProperty").rules("add", {
                required: true
            });
        } else {
            $("#MyOtherProperty").rules("remove", "required");
        }
    });