Search code examples
knockout.jsasp.net-web-apidata-annotationsknockout-validation

Web API + Knockout validation


I am trying to implement a bit nicer validation in relation Model -> WebAPI -> Knockout. Right now I've created data annotation which i plan to update and use IClientValidatable. Problem is that current architecture doesn't know about this model. I have this:

HTML:

<span>Name</span><input type="text" data-bind="value: validationData.name" />

JS:

    self.validationData = {
            name: ko.observable('').extend(
                {
                    required: true,
                    minLength: 3,
                    pattern: {
                        message: 'validation message',
                        params: '^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,6}$'
                    }
                }),

        };

As you may see I am using knockout.validation.js and now i want to remove pattern from code and use it from one location. For instance, I want to have this:

self.validationData = {
            name: ko.observable('').validate()
        };

In general, is it possible to make Knockout to be aware of DataAnnotations from the Model?


Solution

  • You can add functions to observable prototype by usign the .fn object

    ko.observable.fn.validate = function() {
        return this.extend({
            required: true,
            minLength: 3,
            pattern: {
                message: 'validation message',
                params: '^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,6}$'
            }
        })
    };
    

    http://jsfiddle.net/WzLwS/

    But you cant get data-attributes from the view no

    edit: You can get this behaviour if you override the value binding handler, check the observable if its a validatable observable and then extract the data-atributes from the element