Search code examples
javascriptjqueryjquery-validateunobtrusive-validation

Jquery Unobtrusive Validation 'Cannot read property 'type' of undefined'


I am using jQuery Unobtrusive Validation in my MVC application. When posting back, the validation works as-prescribed. However, there are valid reasons for me to prevent a post-back client-side.

I am following the prescribed approach seen across multiple sites...and I have tried many different combinations. However, I still keep getting the following error:

"Cannot read property 'type' of undefined"

MY JAVASCRIPT LOOKS LIKE:
The error happens when I call 'showErrors'...

function onValidateCity(e){

    // Checks the value of my Kendo Combobox
    var value = this.value();
    if (value && this.selectedIndex === -1) {

        // Yes, it reaches this part
        var validator = $('#CityId').validate();
        validator.showErrors({"CityId": "My custom error message!"});
    }
}

MY MVC HELPER CREATES THE FOLLOWING HTML:

<span class="k-widget k-combobox k-header form-control">
    <span tabindex="-1" unselectable="on" class="k-dropdown-wrap k-state-default">
        <input name="CityId_input" class="k-input form-control" type="text" autocomplete="off" title="" maxlength="524288" role="combobox" aria-expanded="false" placeholder="-- Select City --" tabindex="0" aria-disabled="false" aria-readonly="false" aria-autocomplete="list" aria-owns="CityId_listbox" aria-busy="false" style="width: 100%;" /> 
        <span tabindex="-1" unselectable="on" class="k-select">
            <span unselectable="on" class="k-icon k-i-arrow-s" role="button" tabindex="-1" aria-controls="CityId_listbox">select</span>
        </span>
    </span>
    <input autocomplete="off" class="form-control" data-val="true" data-val-required="The City field is required." id="CityId" name="CityId" type="text" value=  "28dbddea-660d-4bbb-b063-f926b1153866" data-role="combobox" aria-disabled="false"
aria-readonly="false" novalidate="novalidate" style="display: none;" />
</span>

<span class="field-validation-valid text-danger" data-valmsg-for="CityId" data-valmsg-replace="true"></span>

MVC (VALIDATION) HELPER LOOKS LIKE:
@Html.ValidationMessageFor(model => model.CityId, "", new { @class = "text-danger" })


Solution

  • When you initialize validator, do it against the element that contains CityId input nested inside, not the input element itself. It can be a form or a div or a span.

    Here's simplified code working in fiddle, I did it against span: http://jsfiddle.net/o0qhcbbL/1/

    $('#button').click(function (e) {
        onValidateCity(e)
    })
    
    function onValidateCity(e) {
    
        var validator = $('#xx').validate();
    
        validator.showErrors({
            "CityId": "My custom error message!"
        });
    }
    

    html:

    <span id="xx">
        <input id="CityId" name="CityId" type="text" />
    </span>
    <span id="button">select</span>