Loading...

RequiredIf validation not failing using jquery


My form keeps returning $(form).valid() = true when it should be failing.

My ViewModel:

public class SearchProvidersViewModel
{
    public bool IsClicked { get; set; }

    [RequiredIf("IsClicked", true, ErrorMessage ="IsClicked is required")]
    public string Name { get; set; }
}

My View:

@using (Html.BeginForm("Search", "Home", FormMethod.Post, new { @id = "SearchForm" }))
        {

<label class="btn btn-primary" id="IsClicked">
                            @Html.RadioButtonFor(x => x.IsClicked, true) Name
                        </label>

@Html.TextBoxFor(x => x.Name, new { @class = "form-control" })
                        @Html.ValidationMessageFor(x => x.Name, "", new { 
 @class = "text-danger" })

<button id="btnSearch" type="submit" class="btn btn-success">Search</button>
}

my javascript:

 $(document).on("click", "#btnSearch", function (e) {
 $("#SearchForm").validate();
        if ($("#SearchForm").valid()) {
//post form to controller
}

The form is always being posted to the controller. If I run $("#SearchForm").validate() in the console, I can see that the currentForm has input#Name and this has the correct attributes:

data-val-requiredif,

data-val-requiredif-dependentprpoperty,

data-val-requiredif-dependentvalue

and the dataset has the correct values for each.

validity: valueMissing is false, even though in my controller when the viewModel is passed back the value for IsClicked is true.

Is it something to do with the validator looking for a value of IsClicked of "True" but I am just passing back true? If so - how do I fix this? Or is it something else completely?

EDIT/UPDATE: So I didn't get a fix for this...I used the following workaround in case it is of use to anybody:

var form = $("#SearchForm");
            validator = $(form).validate();
            validator.settings.showErrors = showErrors;

            var errorMessage = "This field is required";
            var isValid = false;
            if ($("#IsClicked").hasClass("active")) {
                if ($("#Name").val() == "") {
                    validator.showErrors({
                    "Name": errorMessage
                    });
                }
                else {
                    isValid = true;
                }
            }

if (isValid) {
// submit form
                }

function showErrors(errorMessage, errormap, errorlist) {
            var val = this;
            errormap.forEach(function (error, index) {
            val.settings.highlight.call(val, error.element, 
val.settings.errorClass, val.settings.validClass);
            $(error.element).siblings("span.field-validation-valid, span.field-validation-error").html($("<span></span>").html(error.message)).addClass("field-validation-error").removeClass("field-validation-valid").show();
        });
    }
- - Source
comments powered by Disqus