Fluent validation rules registration in view model, jsFiddle included

5,036 views
Skip to first unread message

Andrew Booth

unread,
May 17, 2011, 4:41:58 PM5/17/11
to knock...@googlegroups.com
Hi


I've had a quick try at adding validation to a view model, that allows a fairly fluent registration and binding approach.

Body <em data-bind='text: body.error()'></em<br/>
<textarea data-bind='value: body'></textarea<br/>


viewModel.validation
        .required(viewModel.subject'Required')
        .minLength(5viewModel.subject'Minimum 5 characters')
        .maxLength(10viewModel.subject'Maximum 10 characters');


This is heavily based on a previous jsFiddle from Max Zelinski at http://jsfiddle.net/maxzelinski/GpTP3/.

Hope it works! (Tested in Chrome.)

Are there any other Gists/jsFiddle or other samples of good approaches?

Andy

Steven Sanderson

unread,
May 29, 2011, 12:53:14 PM5/29/11
to knock...@googlegroups.com
Hi Andrew

Nice work! This is very interesting, as a lot of people have expressed a wish to have a recommended way of doing validation. So far I've been guiding people to use jQuery Validation classes on their form fields as this is easy and very robust, but it would be nicer still if it could be based on the view model. I like the direction you've taken it. 

I had some other ideas of my own about ways validation could be set up. My concept was to make observables validatable by adding a sub-observable to them, which is a dependent observable that returns the current error message (if any). There could then be bindings to display those error messages. Here's a possible way it could work: http://jsfiddle.net/5PdrL/ . The code there looks a bit messy, but if the validation library code was moved out into a separate file, and if the rules were actually applied using KO 1.3 extenders, e.g.:

var viewModel {
    firstNameko.observable("Bert").extend({ minLength: 5 },    
    lastNameko.observable().extend({ required: true })
};

... then I think it would be pretty nice. What do you reckon?
Steve

Andrew Booth

unread,
May 31, 2011, 4:59:36 AM5/31/11
to knock...@googlegroups.com
Hi Steve


Thanks for the pointers to use a dependentObservable for the error message with validation, and a custom bindingHandler. That approach does seem to embrace the power of the framework more fully. Works well for my scenarios.

I had a further quick experiment with the code, and plugged in some working extenders with pre-release 1.3 pieces. The other addition was making the list of validators per field an observable.

Cheers.

Andy

Steven Sanderson

unread,
Jun 3, 2011, 5:23:20 AM6/3/11
to knock...@googlegroups.com
That looks great! 

Andrew, would you be interested in creating an official "Knockout Validation" plugin based on this pattern? I think it's something a lot of people would really value. 

If so, I'd be really pleased to have a page about it on knockoutjs.com and generally point people towards it whenever they are looking for a clean way to do dynamic validation.

Steve

Andrew Booth

unread,
Jun 3, 2011, 7:28:26 AM6/3/11
to knock...@googlegroups.com
Hi Steve

Thanks for the positive feedback on the KO validation code. Yes, I would certainly like to explore making this a simple flexible plugin that's useful for people.

In the coming days I'll look into JsSpec and work on it a little further, and post updates to this forum.

Cheers.

Andy

prateek4u...@yahoo.co.in

unread,
Jun 6, 2011, 5:09:17 AM6/6/11
to knock...@googlegroups.com
Hi Andrew & Steve,

I was having problems with validation using knockoutjs. Thank God that I came across this forum. I am a novice & would surely appreciate if you'd help me in validating a combo box created using knockoutjs. One more thing the combo box is being dynamically populated. Can you guys please help me out. A code example would help me understand much better.

Thanks in advance.

Prateek.

Andrew Booth

unread,
Jun 6, 2011, 11:17:33 AM6/6/11
to knock...@googlegroups.com
Hi Prateek

Could you perhaps add some details to the outline code at http://jsfiddle.net/andybooth/YaNte to represent your combo box scenario, so I can see what specific details need implementing?

Cheers.

Andy

Andrew Booth

unread,
Jun 6, 2011, 11:39:55 AM6/6/11
to knock...@googlegroups.com
Hi


I've built out some KO validation prototype code a little further. This is primarily tested on Chrome. It adds the following features:

[1] core validators based on HTML5 input validators (required, min, max, minLength, maxLength, pattern) 
[2] easily localize error messages via ko.validation.messages
[3] either validate fields after applyBinding or only on modifications via ko.validation.validationMessageOnModified option 
[4] add custom validators using validation extender

Hope this feature set keeps it simple whilst covering common scenarios.

Regards,

Andy

Stacey Thornton

unread,
Jun 6, 2011, 12:12:28 PM6/6/11
to KnockoutJS
This will be super awesome if it works in conjunction with HTML5
attributes. By that, I suppose you mean like ... "data-val='true'" and
"data-val-regex=' ... '" ?

Andrew Booth

unread,
Jun 6, 2011, 12:23:21 PM6/6/11
to knock...@googlegroups.com
Hi Stacey

The code includes an optional (experimental) feature that will parse the valid HTML5 input attributes (pattern, required, min, max, maxlength) working on the convention that these should be added to the observable bound to the input using the value binder. This is a convenience method only, so is switched off by default.

ko.validation.registerInputAttributeMappings();

<input pattern="regexExpression" required min="1" max="10" maxlength="20" data-bind='value: observableToValidate'/> 

Regards,

Andy

Roy Jacobs

unread,
Jun 8, 2011, 1:05:45 PM6/8/11
to knock...@googlegroups.com
Andrew,

I have a suggestion:
Right now I feel it is a bit messy to add all the <span data-bind='validationMessage: property'></spanall over the place.

Maybe you can experiment a bit with a binding handler that you would add on, say, the fieldset that would automatically add the spans on the form elements within.
I'm not sure if you can extract the binding parameters of all the form elements (because you'd need to know the name of the property), but it would severely reduce the amount of redundancy, I think.

Then, if you could also specify a 'validationTemplate' then you're also guaranteed all the form elements have a consistent validation message layout.

Roy

Andrew Booth

unread,
Jun 8, 2011, 7:33:44 PM6/8/11
to knock...@googlegroups.com
Hi Roy

Thanks for the suggestion. Yes, eliminating the individual validationMessage bindings and tags would certainly make the markup cleaner. The below code is a quick way, which works with the prototype, adding spans after inputs that have a value binding. Though overriding the value bindingHandler is perhaps a little bit of a hack.

var base = ko.bindingHandlers.value.init;
ko.bindingHandlers.value.init = function (element, valueAccessor, allBindingsAccessor) {
    base(element, valueAccessor, allBindingsAccessor);
    if (isValidatable(valueAccessor())) {
        var span = document.createElement('SPAN');
        insertAfter(element, span);
        ko.applyBindingsToNode(span, {
            validationMessage: valueAccessor()
        });
    }
};

Allowing this to be configured at a fieldset level, and with templates, is something I'll have to work on. I've not worked out what syntax or properties that would require.

Cheers.

Andy

Roy Jacobs

unread,
Jun 9, 2011, 3:24:20 AM6/9/11
to knock...@googlegroups.com
Hi Andrew,

Good work :)

I'm not sure how to access the valueAccessor of a random DOM element, but otherwise you could use that in a binding handler to access all child DOM elements and associated values. This would alleviate the need for overriding the 'value' bindingHandler.

Maybe Steve or rpn have a good idea on how to do this.

Roy

Chris Dew

unread,
Jun 10, 2011, 8:48:18 AM6/10/11
to KnockoutJS
Hi Andrew, (and Roy - thanks for the mapping fix)

I wrote a rather hacky KO validator for a page a few months ago. Some
of its redeeming features were:

1. 'mustEqual' - allowed a field to validate only when it matches
another (i.e. retype your password)

2. distinguished between 'untouched empty' and 'deleted it all empty'
values - this allowed validation messages on compulsory fields to
appear only after the user attempted data entry. (The empty form
wasn't a heap of validation errors before the user started. The
validation errors only appeared after the user had attempted data
entry for a field.)

3. keypress-by-keypress validation - don't wait for the form to be
submitted before validating the current (and dependent) fields. (i.e.
if you change the password field by adding a '3' to the end, the
'retype password' field should become invalid.

4. delayed validation - my validator only attempted validation one
second after the last keypress (a re-armable timeout)

Will this new validator meet these use cases?

There was a lot wrong with my validator (it was a singleton in the
page, for a start), but if you'd like to see the code I'll put up a
gist.

I'm really looking forward to using a complete, supported validator
which uses KnockoutJS's features to provide the best in real time
validation feedback.

All the best,

Chris.

Douglas Livingstone

unread,
Jun 10, 2011, 8:56:29 AM6/10/11
to knock...@googlegroups.com
On 10 Jun 2011, at 13:48, Chris Dew wrote:

> 2. distinguished between 'untouched empty' and 'deleted it all empty'
> values - this allowed validation messages on compulsory fields to
> appear only after the user attempted data entry. (The empty form
> wasn't a heap of validation errors before the user started. The
> validation errors only appeared after the user had attempted data
> entry for a field.)


There is a good example of that here:

http://www.patientslikeme.com/user/signup

I like the validation error messages on blur (the username one is async to check for username already in use). The "Thank you" message on validation pass is also good, and demonstrates the untouched/invalid/valid split. The same mechanism is used on the second stage of the form to display little bar charts and pies to show you what proportion of the userbase has, for example, the same age as you.

Douglas

Chris Dew

unread,
Jun 10, 2011, 9:20:25 AM6/10/11
to KnockoutJS
Hi Douglas,

Yes, that is a nice form, but not perfect.

I would like real-time (per-keypress) async validation of the username
field. (Can I stop typing at 'chris', 'chrisdew' or 'chrisdew42'?)
Yes, serverload...

I would like real-time (per-keypress) validation of the retype-
password field. It should tell me I'm right as soon as the fields are
identical. (Did I type 'aaaaa' or 'aaaaaa' as my password, I can
never remember. I shouldn't have to click outside the box, or count
stars to tell.)

I'm sure this behaviour is a personal preference. Do others like
this?

Perhaps we could parameterise 'per-keypress' validation? Or just hook
it onto the back of "valueUpdate: 'keyup'".

All the best,

Chris.

Andrew Booth

unread,
Jun 10, 2011, 9:30:11 AM6/10/11
to knock...@googlegroups.com
Hi Chris

Thanks for outlining your scenarios that will make the validation code relevant for good form validation usability. I have updated the sample at http://jsfiddle.net/andybooth/2GUyX/ just now (validation library at https://gist.github.com/1009233).

There is full support for [1] 'mustEqual' style validators, using a custom validator as I have now added to the sample. There is partial support for [3], showing validators once a value has been modified. ko.validation.configure({ messageOnModified: false }) shows all messages up front. Setting this to true shows them onchange, or after calling ko.validation.group(context).showAllMessages().

I'd be very interested to see any sample code you have for [2], [3] and [4]. Or do please fork the code at https://gist.github.com/1009233, if appropriate, with ideas.

I'll have to experiment a little myself with update events first before I begin adding these into the code, or where sensible hooks should be.

This revised code also uses ko.validation.configure({ insertMessages: true }) to automatically add <span data-bind='validationMessage: observable'></span> as recommended by Roy. This remains a global flag and can only template the validation message elements by overriding ko.validation.insertValidationMessage or by using validationMessage bindingHandlers declaratively.

Regards,

Andy

Roy Jacobs

unread,
Jun 10, 2011, 9:44:41 AM6/10/11
to knock...@googlegroups.com
Hi Andy,

Looking good! I really like how clean everything is becoming. One thing I would still like to see (and ofcourse I don't have the time to do this myself :)) is that instead of creating SPAN elements in insertValidationMessage, you render a template instead.

The code for that is not very hard, it's just something like:
    ko.renderTemplate(
          "myTemplate",
          model,
          {},
          domElement
        );

And I believe you can pass a fifth argument which allows you to specify if you want to insert or replace. If the template-name can then be part of the "extend" options, then every observable can have its own template, although that might be better configured in HTML.

Roy

Chris Dew

unread,
Jun 10, 2011, 9:45:54 AM6/10/11
to KnockoutJS
Here's the gist - https://gist.github.com/1018787 - the code worked,
but is abandoned. It had a number of major flaws (only one validator
per field, only one form per viewModel, etc.).

2. this was done by using two classes 'valid' and 'invalid' which were
applied only on validation (i.e. the fields did not have these before
they had changed)

3. and 4. I used "valueUpdate: 'keyup'". 'obs.timeout' is the re-
armable timer. The one second timeout (for adding the 'invalid'
class) is reset on every failed validation, and removed entirely on a
successful validation.

Thus the field may have failed validation already but this is not
indicated to the user until they have stopped typing for one second.
For a password field with a minimum of 5 chars, if they type five
character fast, four timeouts will be set, three will be subsequently
re-armed and the last will be cleared when the field validates.

If they type very slowly, the timeouts will run to completion and they
will see a validation error one second after typing the first
character, this will be repeated until the fifth character is
entered.

obs.timeout is around line 152 for valid and 161/164 for invalid.

I'll have a look at your code shortly.

All the best,

Chris.

On Jun 10, 2:30 pm, Andrew Booth <andy.booth...@gmail.com> wrote:
> Hi Chris
>
> Thanks for outlining your scenarios that will make the validation code
> relevant for good form validation usability. I have updated the sample athttp://jsfiddle.net/andybooth/2GUyX/just now (validation library athttps://gist.github.com/1009233).
>
> There is full support for [1] 'mustEqual' style validators, using a custom
> validator as I have now added to the sample. There is partial support for
> [3], showing validators once a value has been
> modified. ko.validation.configure({ messageOnModified: false }) shows all
> messages up front. Setting this to true shows them onchange, or after
> calling ko.validation.group(context).showAllMessages().
>
> I'd be very interested to see any sample code you have for [2], [3] and [4].
> Or do please fork the code athttps://gist.github.com/1009233, if

Roy Jacobs

unread,
Jun 10, 2011, 9:51:03 AM6/10/11
to knock...@googlegroups.com
I think the timeout stuff will be handled very neatly when Steve releases KO 1.3. The 'throttle' extender will solve these problems, I think.

Chris Dew

unread,
Jun 10, 2011, 10:24:37 AM6/10/11
to KnockoutJS
Hi Andrew and Roy,

On first impression, this looks very good indeed.

I've just edited the jsfiddle and added 'valueUpdate: "keyup"' to a
few fields - this gave them working pre-keypress validation.

To make this nice, we'll need a re-armable timeout (or KO 1.3's
'throttle') to stop the validation messages appearing immediately on
each keypress.

This can probably be done by looking for the valueUpdate field from
within the DOM elements data-bind attribute.

This highlights a possible design problem... (I may be wrong on -
I've not tested this.)

* Is validation a property of observables or a property of the DOM
element?

Suppose we had two input fields tied to the same observable. If one
has some html5 validators specified and one doesn't, will the value be
marked as invalid in *both* input fields?

* How well will this 'extend'ing of observables work with ko.mapping?
I do not yet understand ko.mapping, but I'm a little worried that
fromJS() may stomp all over the extended observables. Roy: can you
comment on this?

All the best,

Chris.

Andrew Booth

unread,
Jun 10, 2011, 10:51:56 AM6/10/11
to knock...@googlegroups.com
Hi Chris

Is validation a property of observables or a property of the DOM element
If one has some html5 validators specified and one doesn't
will the value be marked as invalid in *both* input fields

With the current design, parsing validation attributes and inserting validation messages automatically are turned off by default. As it stands, when they are switched on, validation attributes would be parsed and added from both inputs to the same observable, and matching validation messages added to both input. These features are really there for an initial "scaffolded" version of a form. I was though keen to align the validators with HTML5 eg. use of "pattern" terminology rather than regex, hence the feature. Ultimately, I would recommend adding the validation to the viewModel programmatically and the validationMessage bindings to the form html declaratively, to provide full customisation.

Andy

Chris Dew

unread,
Jun 10, 2011, 12:08:15 PM6/10/11
to KnockoutJS
Hi Andrew,

Yes, that makes sense.

While I do have multiple bindings to single observables, I have not
yet found a case where I have needed two 'input' bindings to the same
observable - so this may all be unimportant.

Do you have any idea about ko.mapping's fromJS()'s interaction with
validation extends? Will I need to add the extend's back after each
fromJS()?

Thanks,

Chris.

Andrew Booth

unread,
Jun 10, 2011, 12:45:33 PM6/10/11
to knock...@googlegroups.com
Hi Chris

Quick answer is, I've not tested this fully against Knockout Mapping yet, but definitely will. My understanding of KO Mappings is that if a property isWriteableObservable, it will set the observable as normal, preserving extenders, so validation extenders will be maintained.

(Extenders are a planned feature for Knockout 1.3 https://groups.google.com/forum/#!topic/knockoutjs/pa0cPkckvE8. The validation sample code uses a build I made from the 1.3 branch https://github.com/SteveSanderson/knockout/tree/1.3. KO 1.3 builds are definitely required for this prototype code.)

Andy

Roy Jacobs

unread,
Jun 10, 2011, 12:57:29 PM6/10/11
to knock...@googlegroups.com
Hi Chris,

About the mapping: "ko.mapping.updateFromJS" will update an observable just like you would do manually, so extenders will not be affected.

Roy

Chris Dew

unread,
Jun 16, 2011, 7:05:51 AM6/16/11
to KnockoutJS
Andrew,

I've just thought of one other use case...

Will there be any way of using the same validation in server-side
Javascript, to guard against malicious hand-crafted forms?

It is really essential to use the same form specification, to avoid
duplication. It'd be great to do this without running KnockoutJS
server-side.

It might be possible to mock up ko.observable() on the server side,
use the *same* viewModel code and call a 'validator' function with the
(JSON) form values and the view model.

Do you have ideas on a tidier approach?

All the best,

Chris.

Andrew Booth

unread,
Jun 16, 2011, 7:44:18 AM6/16/11
to knock...@googlegroups.com
Hi Chris


Common validation rules between server and client is something I'm keen on tackling, but probably outside the scope of the current validation KO prototypes.

Whilst on the .NET platform DataAnnotations can be used on models, these rules can be exposed in different ways eg. via MVC views validators or WCF DataService (OData) schemas. So it's a complex area.

I've looked at projects like JSON Schema recently, but unsure whether there is momentum behind them.

In the case of ASP.NET MVC 3, which is my main platform, I have been using DataAnnotations and the included HtmlHelper to add the HTML5 input attributes (type, required, pattern, min, max etc.) to scaffolded forms using Html.EditorForModel(), with the custom string editor saved at Views/Shared/EditorTemplates/String.cshtml. This calls Html.ValidationAttributes(). Then using the HTML5 parsing feature of the prototype KO validation library, these base rules are shared between server and client.

Hope this is of interest.

Andy

Chris Dew

unread,
Jun 16, 2011, 8:53:50 AM6/16/11
to KnockoutJS
Hi Andrew,

When I next work on a project where I need a validator I will attempt
to add a 'extend with validation from JSON schema' method.

There will be issues around warning messages (perhaps override some
sane (English) defaults in a separate parameter object) and possibly
around checking that retype-password and password are identical. (I
don't think I quite understand http://tools.ietf.org/html/draft-zyp-json-schema-03#section-5.8
yet.)

The same schema can then be used client and server-side.

All the best,

Chris.

eric.m....@gmail.com

unread,
Oct 25, 2011, 4:55:58 PM10/25/11
to knock...@googlegroups.com
1.3 has gone through quite a few tweaks since June, so with Andrew's support I've updated the plugin pretty heavily and added some unit tests:

new Fiddle is here:
http://jsfiddle.net/ericbarnard/KHFn8/

and we now have a GitHub repo here:
https://github.com/ericmbarnard/Knockout-Validation

Backward compatibility seems to be working well, so feel free to let me know any questions.

Eric

max.p...@gmail.com

unread,
Nov 3, 2011, 6:36:00 AM11/3/11
to knock...@googlegroups.com
Hi ! Great work! I have some issue with validator. Basically I want validate not model itself but nested object how I can do it. Please see example here http://jsfiddle.net/baio/Eytek/10/

And another question, I wander how it is possible to implement some validation message based on java script action. For example if I want show error in the tooltip message, and this tooltip could only be shown throgh javascript.

Thanks.

Andy Booth

unread,
Nov 3, 2011, 7:47:34 AM11/3/11
to knock...@googlegroups.com
Hi Max

Validation messages are only displayed on screen if you do either of 4 things:
[1] insertMessage = true (the default configuration) and a value binder on an input control is used 
[2] use a text binder bound to the error observable on the extended observable for which you have configured validation
[3] use a custom error messageTemplate
[4] bind to a ko.validation.group and render the text to screen

[1] and [2] are demonstrated below. If you use options [2] or [3], bound to a custom elements in your markup, you could attach a jQuery behaviour or plugin to these element that renders the message as a tooltip, rather than a plain bold tag as below.

Andy

<div data-bind="with: item">
    <button data-bind="click: validate">Validate!</button>
    <input data-bind="value: name"/>
    <data-bind="text: name.error"></b>
</div>

max.p...@gmail.com

unread,
Nov 3, 2011, 8:29:27 AM11/3/11
to knock...@googlegroups.com
Hi Andy!

Thank you for response. It solves my current problem. But still I wont to understand
[2] use a text binder bound to the error observable on the extended observable for which you have configured validation

Sounds little complex to me, could you explain please how it works in code.

[4] bind to a ko.validation.group and render the text to screen

The samething how I can bind to group, custom bindings? 

 you could attach a jQuery behaviour or plugin to these element that renders the message as a tooltip, rather than a plain bold tag as below.

Yes I could, but still I needed some trigger event to show these plugins, when error happens, how it could be done.

For examp:

$(".error-msg").tip();

.....some binding or event ?......
   $(element).tip("message", text?);
   $(element).tip("show");

Thanks again.

 

max.p...@gmail.com

unread,
Nov 3, 2011, 8:52:24 AM11/3/11
to knock...@googlegroups.com
And I can't find how to use messageTemplate parameter, can you point me out where I could see it?

Andy Booth

unread,
Nov 3, 2011, 12:02:36 PM11/3/11
to knock...@googlegroups.com
Hi Max

> [2] use a text binder bound to the error observable on the extended observable for which you have configured validation

This is the <data-bind="text: name.error"></b> approach, where name has been extended eg. viewModel.name.extend({ maxLength: 3 }).

[4] bind to a ko.validation.group and render the text to screen

<div data-bind="with: item">
    <button data-bind="click: validate">Validate!</button>
    <input data-bind="value: name"/>
    <b>Total errors: <span data-bind="text: errors().length"></span></b>
    <ul data-bind="foreach: errors">
        <li data-bind="text: $data"></li>
    </ul>
</div>

If you created item.errors = ko.validation.group(this), as in your code, you can bind to these messages with a foreach binder.

> I needed some trigger event to show these plugins, when error happens

viewModel.item.name.isValid.subscribe(function (valid{
    if(!valid{
        alert(viewModel.item.name.error);    
    }
});

You can subscribe to the isValid observable added when you extend a normal observable with the validation plugin.

A custom template for error messages using messageTemplate is shown on http://jsfiddle.net/ericbarnard/KHFn8/.

Hope that helps.

Andy

max.p...@gmail.com

unread,
Nov 7, 2011, 2:09:36 AM11/7/11
to knock...@googlegroups.com
Hi Andy. Thank you for detailed responce, it is great help for me.

I have one more question. If I had nested object (for model) it seems that validationTemplte parameter doesn't work. It works only when I specify message patter explicitly for element. Please see here http://jsfiddle.net/baio/Wcz95/9/

Thanks!

Andy Booth

unread,
Nov 7, 2011, 2:37:41 AM11/7/11
to knock...@googlegroups.com
Hi Max

Your templated blue error messages show if you make the following change. The ko.validation plugin only triggers messages when used with the value binder, not the text binder. 

From:

<td data-bind="text: name"></td>

To:

<td>

     <input data-bind="value: name"/>
</td>

Hope that helps.

Andy

max.p...@gmail.com

unread,
Nov 7, 2011, 4:48:32 AM11/7/11
to knock...@googlegroups.com
Hi Andy. Thank you for clarification.

And another question about nested objects. What is the best way to link error templete when html element is binded to the nested object like here :
http://jsfiddle.net/baio/Wcz95/13/ . There is, I suppose, should be used general message template  for <div data-bind="value: editItem().name>
but it is not. Only when I do it explicitly (uncomment commented) the message is shown. What is the best way to solve this?

Thanks.

andy....@clusta.com

unread,
Nov 7, 2011, 4:59:54 AM11/7/11
to knock...@googlegroups.com
Hi Max

The error messages display next to the editItem correctly if the bindings are modified to the below.

From:

<div>
    <input type="text" data-bind="value: editItem().name">
</div>

To:

<div data-bind="with: editItem">
    <input type="text" data-bind="value: name">    
</div>

Hope that helps.

Andy




max.p...@gmail.com

unread,
Nov 7, 2011, 7:48:09 AM11/7/11
to knock...@googlegroups.com
Andy, it's work! Thank you for help. Great work indeed, your plugin, keep it in progress.
Max

Peter S

unread,
Nov 7, 2011, 9:57:23 AM11/7/11
to KnockoutJS
This plugin looks really cool, I'm using JQuery validation at the
moment but have been thinking about trying to move my validation rules
to my model for various reasons.

I have a couple of questions though:

Can the extenders be applied to dependentObservables as well?
Is there an easy way to apply validation rules across multiple records
rather than just a single entity. Eg. If I have an observableArray of
person objects and I need to specify that there should be no duplicate
email addresses, how easy would it be to create such a rule and to
pick out the records that don't comply?

Cheers,
Pete

Andy Booth

unread,
Nov 7, 2011, 11:18:15 AM11/7/11
to knock...@googlegroups.com
Hi Peter

No, unfortunately dependentObservables and observableArray constraints with this ko.validation code are not really possible I believe, as it stands. I did have a quick attempt just now, but nothing concrete. The current target scenario is field validation with value binders, custom field validation rules, validation groups, custom error templates.

Andy

srira...@gmail.com

unread,
Feb 14, 2013, 8:30:11 AM2/14/13
to knock...@googlegroups.com
Hi i am very new to knockout js. can anyone help me out in knockoutjs validation tutorial? and i need to pass a dynamic values in the observableArray(). How can i implement this?

On Wednesday, May 18, 2011 2:11:58 AM UTC+5:30, Andy Booth wrote:
Hi


I've had a quick try at adding validation to a view model, that allows a fairly fluent registration and binding approach.

Body <em data-bind='text: body.error()'></em<br/>
<textarea data-bind='value: body'></textarea<br/>


viewModel.validation
        .required(viewModel.subject'Required')
        .minLength(5viewModel.subject'Minimum 5 characters')
        .maxLength(10viewModel.subject'Maximum 10 characters');


This is heavily based on a previous jsFiddle from Max Zelinski at http://jsfiddle.net/maxzelinski/GpTP3/.

Hope it works! (Tested in Chrome.)

Are there any other Gists/jsFiddle or other samples of good approaches?

Andy
Reply all
Reply to author
Forward
0 new messages