KendoUI MVVM validation using Datasource Model validation rules

2.2k Views Asked by At

Just a little hack for validating against a kendo.data.Model

So instead of adding the HTML5 required attribute to each input field manually this little hack gets all the validation rules that you defined in your Model and add them as attributes to the appropriate field. Not fully tested just a quick hack. According to Kendo the validation rules don't get processed if you are using MVVM, but they do if for example you bind the Dataource directly to a grid.

Code: I just put this code in a file called definevalidation.js

function getValidationAttributesFromModel(myFields) {
    var myValidatedFields = [];
    var obj = null;
    $.each(myFields, function(fieldName) {
        if (this.validation) {
            var obj = {
                fieldName : fieldName,
                validation : this.validation
            };
            myValidatedFields.push(obj);
        }
    });

    addValidationAttributes(myValidatedFields);
}

function addValidationAttributes(myValidatedFields) {
    $.each(myValidatedFields, function(index) {
        $('#' + this.fieldName).attr(this.validation);
    });
}

Usage: If ParentDS is your datasource then in your form code just use

getValidationAttributesFromModel(ParentDS.options.schema.model.fields)

Sample Model:

mydatamodel = kendo.data.Model.define({
            id : "__KEY",
            fields : {
                __KEY : {
                    type : "string"
                },
                __STAMP : {
                    type : "number"
                },
                ID : {
                    editable : false,
                    nullable : true
                },
                firstName : {
                    type : "string",
                    validation : {
                        required : true
                    }
                },
                middleName : {
                    type : "string"
                },
                lastName : {
                    type : "string"
                }
            }
        });
0

There are 0 best solutions below