Giter Club home page Giter Club logo

knockout-validation's Introduction

Knockout Validation

A KnockoutJS Plugin for model and property validation

Build Status Build status Bower version npm version NuGet version

Contributors:

License: MIT

Install

Bower

bower install knockout-validation --save

NuGet

PM> Install-Package Knockout.Validation

NPM

npm install knockout.validation --save

CDN

Getting Started

//start using it!
var myValue = ko.observable().extend({ required: true });

//oooh complexity
var myComplexValue = ko.observable().extend({
                     required: true,
                     minLength: 3,
                     pattern: {
                          message: 'Hey this doesnt match my pattern',
                          params: '^[A-Z0-9].$'
                     }
                 });

//or chaining if you like that
var myComplexValue = ko.observable()

myComplexValue.extend({ required: true })
            .extend({ minLength: 3 })
            .extend({ pattern: {
                 message: 'Hey this doesnt match my pattern',
                 params: '^[A-Z0-9].$'
            }});

//want to know if all of your ViewModel's properties are valid?
var myViewModel = ko.validatedObservable({
   property1: ko.observable().extend({ required: true }),
   property2: ko.observable().extend({ max: 10 })
});

console.log(myViewModel.isValid()); //false

myViewModel().property1('something');
myViewModel().property2(9);

console.log(myViewModel.isValid()); //true

see more examples on the Fiddle: http://jsfiddle.net/KHFn8/5424/

Native Validation Rules

Required:

var myObj = ko.observable('').extend({ required: true });

Min:

var myObj = ko.observable('').extend({ min: 2 });

Max:

var myObj = ko.observable('').extend({ max: 99 });

MinLength:

var myObj = ko.observable('').extend({ minLength: 3 });

MaxLength:

var myObj = ko.observable('').extend({ maxLength: 12 });

Email:

var myObj = ko.observable('').extend({ email: true });

... and MANY MORE

Much thanks to the jQuery Validation Plug-In team for their work on many of the rules

Custom Validation Rules

Custom Rules

Custom Rules can be created using the simple example below. All you need is to define a validator function and a default message. The validator function takes in the observable's value, and the params that you pass in with the extend method.

ko.validation.rules['mustEqual'] = {
    validator: function (val, params) {
        return val === params;
    },
    message: 'The field must equal {0}'
};
ko.validation.registerExtenders();

//the value '5' is the second arg ('params') that is passed to the validator
var myCustomObj = ko.observable().extend({ mustEqual: 5 });

Learn more about Custom Rules on the WIKI

Or Check out our User-Contributed Custom Rules!

HTML5 Validation Attributes

Required:

<input type="text" data-bind="value: myProp" required />

Min:

<input type="number" data-bind="value: myProp" min="2" />
<input type="week" data-bind="value:myWeek" min="2012-W03" />
<input type="month" data-bind="value:myMonth" min="2012-08" />

Max:

<input type="number" data-bind="value: myProp" max="99" />
<input type="week" data-bind="value:myWeek" max="2010-W15" />
<input type="month" data-bind="value:myMonth" min="2012-08" />

Pattern:

<input type="text" data-bind="value: myProp" pattern="^[a-z0-9].*" />

Step:

<input type="text" data-bind="value: myProp" step="3" />

Special Note, the 'MinLength' attribute was removed until the HTML5 spec fully supports it

Knockout Bindings

ValidationMessage

If you want to customize the display of your objects validation message, use the validationMessage binding:

<div>
   <input type="text" data-bind="value: someValue"/>
   <p data-bind="validationMessage: someValue"></p>
<div>

Check out more on Validation Bindings

Remote Validation Rules

Check out our Async Validation and jQuery AJAX Validation

Localization

Add a reference to the localization js files after the Knockout Validation plugin

<script type="text/javascript" src="knockout.validation.js"></script>
<script type="text/javascript" src="el-GR.js"></script>
<script type="text/javascript" src="fr-FR.js"></script>
<script type="text/javascript" src="de-DE.js"></script>

Apply localized messages

ko.validation.locale('el-GR');

knockout-validation's People

Contributors

aavezel avatar arfilon avatar barkbarkuk avatar bogatykh avatar brettmorien avatar codethug avatar crissdev avatar davhdavh avatar delixfe avatar dgaviola avatar dtritus avatar ericmbarnard avatar grofit avatar ifyates avatar jpaugh avatar kozlowski-mathias avatar laurenrevere avatar lcorneliussen avatar luizbon avatar michalporeba avatar peterdavehello avatar phille88 avatar richardlawley avatar solidsoils avatar stevegreatrex avatar tdoumas avatar terencelewis avatar warappa avatar yuks avatar zzapal avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

knockout-validation's Issues

Please help a js noob understand how to use knockout-validation.

I created a jsFiddle example of something I'm trying to do. Its a simplified version of what Im doing. I'm having trouble because the code I use to hook up to the submit button is located inside my viewmodel. Looking at your examples it seems that the validation has to wrap the viewmodel with the validatedObservable call.

http://jsfiddle.net/evanlarsen/7bQTg/

I'm not sure how to wrap my view model and be able to validate it from within the viewmodel. Any suggestions would be much appreciated. Also, if you have any ideas on how I could beter structure my JS I would be greatful.

Thanks,
Evan

Changing validation rules on the fly

I'm trying to update the validation rules of some fields that depend on the values of others on the fly, with no success. Sample code is at http://jsfiddle.net/2vfaV/3/
"deneme" is the main field and validation of "bagimli" depends on the value of deneme. How can i update the validation rule of bagimli?

Init/Configure really needed?

Currently you have to call 'init' or 'configure' to do the following:

registerExtenders();
registerValueBindingHandler();

could we simply register the extenders and value binding handlers during compilation, and then just supply the configs right before ko.applyBindings(viewModel); is called?

Like:

ko.validation.applyValidation({ insertMessages: false });
ko.applyBindings(viewModel);

Should showAllMessages also be recursive?

I have noticed in the 1.0 branch that group seems to now allow recursive observable checks which I am currently suffering with as I have a quite complex model I am representing. However this recursive check does not seem to be applied to showAllMessages.

Also should this also be applied to ko.validation.validateObservable()?

Sorry to bombard you with issues :)

Can you get the element the data is bound to?

Not an issue exactly, but is there any way to get the element the data is bound to when getting the validation errors?

I am currently using Jquery Validation with callbacks to get another library display nice tooltip validation errors, but it is not nice and I would rather drive the validation from the models not the UI elements.

So I really like the approach of pushing the validation down to the models, but ideally I need a way to tie the error I get to a given element in the UI. So is there a way to do this?

v1.0 : error messages are not switched correctly

When there is more then one validator error message are not switched correctly on v1.0.

Repro steps :
Go to your example which is using v0.9 :
http://jsfiddle.net/ericbarnard/KHFn8/

Type in -1 in Age and press enter. Min error message shows. Correct.
Now type in 101 in Age and press enter again. Max error message shows. Correct.

Now change the reference from v0.9 to v1.0 and perform the same test.

Bug : Min error message won't change to max error message.

pattern rules fails with non string types

the pattern rule only applies til string type values, and it breaks bad when applying to other types.

should it convert val to string before validating or should there be another pattern rule that can be used for other types?

Add custom errorElement selector / Errors on submit

Hi,

Thanks for the great plugin, just a couple of questions:

  • What's the best approach to customise which element has the 'errorElementClass' css class applied to it. We are using Bootstrap and have the following code:
<div class="control-group">
       <label class="control-label" for="age">Age</label>
       <div class="controls">
             <input type="text" class="input-small" id="age" data-bind="value: age">
       </div>
   </div>

We would like to add an 'error' css class to the control-group rather that the input. I have hacked in an update to the knockout-validation js to get it working but it is not the best solution

  • Your example here (http://jsfiddle.net/ericbarnard/KHFn8/) is displaying the number of errors even though the form has not been submitted. Is there a nice way of only filling the errors collection when the form has been submitted at least once?

Cheers.

Validation Error Display Section

Dears,
How can i put all validation error messages in a particular section?
is there any sample that illustrate the following attributes
- registerExtenders
- messagesOnModified
- insertMessages
- parseInputAttributes
- messageTemplate

Best Regards

v1.0 : validationElement vs validationMessage behavior inconsistency

I like a lot what you are doing here!

I like the way error message span in v1.0 is hidden until message should be displayed.
That's helpful when span is styled to have a border etc.

I would expect similar behavior with validationElement binding.

Here is my example initial state of the form :
<input type="text" data-bind="value: InvoiceNo, validationElement: InvoiceNo" id="InvoiceNo" class=" validationElement"/>
<span class="field-validation-error" style="display: none;"></span>

Error message is hidden with styles which is expected behavior - user hasn't modified the form yet so although the field is invalid don't tell him to fix it.
But on the element itself errorElementClass has been already added.
Can you see the problem with consistency there?

computed vs dependantObservable

with KO 2.0 with have now computed as an alias for dependantObservable.
For me it is not only shorted but better describing name.

What do you think about using the newer name in the validation code? I don't like idea of mixing so either I would like to change it all to computed or stick to dependentObservable. Obviously after the change it would not work with KO 1.x

How does isModified work?

Just before I get to the main question here is a bit of context and it may just be me being an idiot, but I have a case at the moment where I have a custom binding hooked up which subscribes the observable to IsValid changing:

/*globals ko $*/
var originalKoValueInit = ko.bindingHandlers.value.init;
ko.bindingHandlers.value.init = function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
    originalKoValueInit(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext);

    var observable = valueAccessor();
    if (!ko.validation.utils.isValidatable(observable)) { return; }

    var $element = $(element);
    observable.isValid.subscribe(function (valid) {
        if (!valid) { 
            // Raise a validation error event here
        }
        else { 
            // Raise a validation success event here
        }
    });
}

Now this works great, whenever the observable is changed it will raise the relevant error. However I have a scenario where if someone doesn't use a field with validation on and submits, as it is not having its value changed it will not trigger any isValid subscriptions, but the errors from the group(someModel); will reflect the error with the field correctly, however in my specific scenario no errors would appear on the page (assuming the raise validation error displays some form of validation error) even though the form cannot submit because they need to sort out the errors.

With the above scenario I want any validation errors to be displayed when the users click on the submit button. I am basically doing if(errorsFromGroup().length == 0) { Progress(); } else { Fail(); } so I thought I could just put errorsFromGroup.showAllMessages() before the example Fail() outcome. However this doesn't seem to do anything in my scenario, I looked in the source code and saw that when you do showAllMessages it just loops through all observables and sets the isModified observable to true, but I cannot see anything subscribing to this observable.

The thing that puzzles me is that within your example JSfiddle document, you use this showAllMessages to display all the inline validation errors on the page, so I was assuming in a round about way the isModified property influences some logic within the validation framework, but I just cannot find it anywhere... So am I missing some crucial part or is this observable not used anywhere, and some other voodoo magic is making your inline validation messages appear?

As far as I am concerned the main thing I want to do is get the isValid subscriber to fire whenever I press this imaginary submit button, is this possible? as there must be some crucial bit I am not seeing which hooks the observables value changing to trigger an isValid check, but for the life of me cannot see it...

Add capability to use knockout visibile binding

Right now knockout validation has a span that contains the error message and is visible at all times, is there an easy way to make it so the span containing each error is not visible until it has a message? Not sure if this is a feature request but I haven't found a way to get it working like this.

Thanks for such a great tool.

can i display RESTful web service returned validation errors?

So, when I POST lets say this model to my RESTful webservice:
{ Office: { Description: '', Location: 'somewhere', Manager: '' } }
Description and Manager being a required field.. The webservice will return back something like this:
[ { 'Office.Description' : 'Description is a required field' }, { 'Office.Manager' : 'Manager is a required field' } ]

I want to display this error on the page and next to the input field which Description is bound to. I can think of an easy way to show all the validation messages in a validation summary at the top of the forum, but I would rather change the border of the input box which the Description observable is bound to.. and also display the validation message next to the input field.

I can't think of an easy way to do this which will be re-usable throught my site.

Do you know of any ways in which I could use Knockout-Validation to handle this scenario?

Thanks,
Evan

Change in 'error' class between master and v1.0

Hi,

I was previously using the master validation library with Twitter bootstrap, and when the validation messages are inserted into the dom, they take the class values that are defined for the enclosing div tags. However, this is no longer the case for v1.0.

Can you give me an outline of the major changes between master and v1.0 with regards to the validation message css. I can't see from the code where the change is breaking the css.

Cheers

showAllMessages to take bool to hide all messages

I have a scenario where I am preloading a form with some data for a new entity. The loader ends up assigning all fields from JSON returned from the server (hence setting isModified to true for all fields), but does not check if there is actually a value. The result is that those required fields with empty data end up with their validation message shown - when I really want it to behave as a 'new' form. It seems one solution is to allow showAllMessages to take a boolean as shown below - which would allow us to pass in false to hide all messages. Any thoughts?

                result.showAllMessages = function (show) {
                    if (show == undefined) //default to true
                        show = true;
                    ko.utils.arrayForEach(validatables, function (observable) {
                        observable.isModified(show);
                    });
                };

Thanks,
Scott

Adding Other events

Hi Eric,

Will you add keydown, keyup and other events?

I would like to show the error message on afterkeydown.

Thanks,
Kaung

Should everything except Required rule pass with empty string or undefined?

I was just looking at a scenario I have, where I have a large document which is saved and viewed by users. Now I have quite a few fields which are not required to be filled in, however if they are I need them to adhere to a certain rules.

Take the below as an example:

function SomeCarModel() {
    this.Name = ko.observable().extend({ required: true, minLength: 6, maxLength: 20 });
    this.Year = ko.observable().extend({ required: true, min: 1950, max: 2050 });
    this.MaxSpeed = ko.observable().extend({ min: 30, max: 300 });
}

Now in the above example the Name and Year are both required, and also need to be within the relevant constraints. However the MaxSpeed is an optional property which would not need to be entered BUT if it were entered then I would require it to be between 30 and 300.

Forgetting the imaginary example above, I have a lot of these optional fields, and people frequently type things in and save it, then may come back later and remove the value entered. So in this case it would flag a validation error even though I have not set the validation to be required.

adding validation to array items

I've been working on adding validation to new items dynamically added to an array of items and I'm having a bit of an issue.

http://jsfiddle.net/gFzQE/

In the fiddle you'll see 3 buttons:
addWorks adds an item and adds the validation before pushing it into the array

addFails pushes the item into the array and then adds validation

addFails2 pushes the item into the array and then loops through all items in the array to add validation

Am I doing something wrong with these 2 failing methods by trying to add validation after it's been added to an observable array or is this a bug?

How do I validate nested entities?

@ericmbarnard
I'm trying to get my nested objects to be validated but I'm not having any success. Can you please take a look at this example and tell me what I'm doing wrong?

I was looking at the tests built for Knockout-Validation and I guess this is the scenario I would imagine to happen. If I was to write a test case for my example.

test('validatedObservable inside a validatedObservable is made InValid', function () {
    var obj = ko.validatedObservable({
        testObj: ko.observable('').extend({minLengh: 5}),
        testObj2: ko.observable('').extend({ requried: true }),
        nestedObj: ko.validatedObservable({
            ntestObj: ko.observable('').extend({minLengh: 5}),
            ntestObj2: ko.observable('').extend({ required: true })
        })
    });

    obj.testObj('something')
    obj.testObj2('eric')

    ok(obj(), 'observable works');
    ok(!obj.isValid(), obj.errors()[0]);
});

extend functions

This is just an idea of code (and coding) simplification.

at the moment there are two extend functions when one works with knockout.validation

  • ko.utils.extend() - from original knockout
  • ko.validation.utils.extend() - from the extension
    and if one assumes that most people using the two use also jQuery at least from time to time, there is also
  • jQuery.extend()

the not obvious problem is that not only the three functions are implemented differently but the actually do different things.

jQuery.extend() is by far most advanced, accepts many sources and can perform truly deep copies. It doesn't copy undefined properties and makes sure it is always copying values not references
ko.utils.extend() performs only quick shallow copy of immediate properties of the only one source object. the only check id does is hasOwnProperty
ko.validation.utils.extend() is a strange hybrid that takes up to two sources and copies properties of the immediate properties and properties of properties. But it is not recursive so third level properties will not be processed.

obviously there is no point adding dependency on massive jQuery library just to have one function available, especially that one of the nicities of knockout is that is self contained. But how about either using ko.utils.extend or if it is for any reason impossible (for example you need the second level properties) maybe we could suggest changes to ko.utils.extend() implementation?

Example custom template

Hi,

Would you mind providing an example of a custom template? from what i can see, looking at the source.. the only thing passed in is valueAccessor() which seems to just be the value.

Ideally you'd receive an error message and the field name.

To test, currently i have a template:

        <span class="left field-validation-error">*</span>
    </script> 

and it does render the asterisk.. but it renders it regardless of whether the field is valid or not.

Validation of nested objects.

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.

Custom Rule Binding not working

I am having lots of trouble getting any custom rule bindings working.

When I inspect the ko.validation object I can see the rule that I have created but it is not getting fired.

Here is the modified example with the mustEqual custom rule binding added to the age field (must equal 25).

http://jsfiddle.net/KHFn8/231/

Any thoughts? What am I missing?

new at ko and validation...should be quick fix.

Hi,

your plugin looks great! however i can't do it justice atm. Im struggling to do a simple validation when applying a form item in a template data loop. My production form is made up of many dynamic templates depending on the input type. I think if i can get a simple version working I should be able to roll it into the more complex form.

http://jsfiddle.net/johnstontrav/JHSxH/2/

The error text is display, but on submit its return valid even though the input error is true. Any help would be great!

Add 'step' rule

HTML 5 input validation attributes seem to allow a 'step' attribute that denotes a valid increment for a number.

We could implement this as:

ko.validation.rules['step'] = {
    validator: function(val, step){
        return val % step === 0;
    },
    message: 'The value must increment by {0}'
};

0 as number should be truthy

this:

required && val && (val+'').length > 0

returns false if val == 0

but sometimes 0 is a normal value of the form
so we should check this case:

if (val == 0) val = val + '' ;

Custom validation messages?

Can I use custom error messages per property?
For example, I have 2 properties, username, and password. By default, both throws same error message saying "This field is required". Is there any way to use custom messages with individual properties?

         username: ko.observable("")
                .extend({
                    required: true
         }),
         password: ko.observable("")
                .extend({
                    required: true
         })

isValidating observable not reset to false

In validateAsync, the callback does not reset the isValidating observable to false if a) the observable being validated is already not valid, or b) the callback returns isValid == true.

observable.isValidating(false); needs to be added before the return statement in the conditionals that test for the above two conditions.

Reset Validation State

so, i've got a view model where i occasionally need to reset the validation state of the object to unmodified so that it behaves as a new form, i was wondering what the accepted method for that was.

How can I create a complex custom template?

My custom message template is complex:
i.e.: div > p > span + strong(data-bind=validationMessage:field)

It works. The message is on the strong but also the hidden style.
I want the hidden style in the main div.
How can I achieve that?

Here is a jsfiddle to illustrate the problem http://jsfiddle.net/ygvR3/

Thanks in advance,

Pedro

Number in required field isn't valid

item.period('14')
item.period.isValid() -> true

item.period(14)
item.period.isValid() -> false

error in line 223:
ko.validation.rules['required'] = {
validator: function (val, required) {
return required && val && val.length > 0;
},
message: 'This field is required.'
};

Number doesn't have 'length' property.

Label appearance and required input

Hello,

I would like to automatically change the appearance of my labels (by adding an * for example) if the associated input (defined by the 'for' html tag) is bound to a required field.
Any idea to do this ?

errorMessageClass not getting used

First off excellent work thank you.

I was try to use the errorMessageClass option but it didn't seem to be working unless the configuration was set using init (prior to calling applyBindings).

I traced the issue to:

       insertValidationMessage: function (element) {
            var span = document.createElement('SPAN');
            span.className = configuration.errorMessageClass;
            utils.insertAfter(element, span);
            return span;
        }

This seems to use the "static" configuration. Changing the class line as below seems to have resolved my problem...

span.className = utils.getConfigOptions(element).errorMessageClass;

Validation with custom extension seems not showing error message on screen

Hi,

I was doing some evaluation about knockoutjs and validation, Thanks for your plugin it is really helpful.

One use case seems not working in my case - i have used autonumeric extension from (https://gist.github.com/1341303)
When i apply validation rules to autonumeric field in ko.validation.group(model) it gives error message properly. but somehow it is not showing on screen.

can you please help me out for this.

Thanks and regards

Adding 'error' class to the invalid form element

I added this feature by adding custom binding and applying it on line 189

ko.applyBindingsToNode(element, { errorClass: valueAccessor()});

and later on line 286

ko.bindingHandlers.errorClass = { // add/remove 'error' class to the element 
        update: function (element, valueAccessor) {
            var obsv = valueAccessor();
            obsv.extend({ validatable: true });
            if (obsv.isValid()) {
              $(element).removeClass('error')
            } else {
              $(element).addClass('error')
            }
        }
    };

I am sure u can implement this feature in the nicier way, I am just learning javascript :)

validation chaining issue with required and email rules

When you have an expression like this...

    this.Email = ko.observable()
                .extend({ required: true })
                .extend({ email: { message: 'Invalid email address.' } })

...and the variable has a string value that is not a valid email, you get a 'required' error message rather than an email invalid message. Any ideas as to what is causing this?

Adding minCount, maxCount validation to observableArrays

Would it be possible to add validation rules for observableArrays, so you could say that an observable array should have a minCount or maxCount? i.e:

function SomeViewModel() {
    var self = this;
    self.Addresses = ko.observableArray().extend({minCount: 1, maxCount: 3});
    self.ViewModelErrors = ko.validation.group(self);

    self.SubmitViewmodel = function() {
        if(ViewModelErrors().length > 0) {
            alert("Please ensure you only have at least 1 address and no more than 3");
            return;
        }
        // Do some submission stuffs
    };
}

I have a scenario where I would ideally like the limit the amount of elements they can create within observableArray, currently I just check on the size every time they alter the array and deal with it manually, but it would be nice if I could farm some of that logic off to the validation library.

Validating hierarchical view models

Hi Eric, I thought I will discuss few things before I send you any pull requests.

I have currently changed implementation of ko.validation.group() to make it process complex hierarchical objects and view models. Currently it traverses objects tree checking each property and each array member and works fine but I was thinking... will it break anything in other people's use cases?

At the moment it checks either an array or direct properties of the view model. I thought that is not enough as when you attempt to validate the whole view model you really think about the whole structure rather than the outer layer so I would be happy to simply replace the group function implementation, but with that there maybe a small performance hit so for some people it may be a big deal.

Are you using validation with KoGrid? There I suppose with thousands of objects it could be significant

parseInputAttributes compares as strings instead of numbers

I've been using the parseInputAttributes option to extract some Min and Max validation rules from the markup. The problem is this always seems to extract the value for comparison as a string.

The example below will extract the Max value for comparison as "100" (a string) so if the user enters 99 in the input then validation will fail because "99" is greater than "100" when comparing as strings.

<input data-bind="value: amount" type="number" min=0 max=100 />

A (not ideal) solution is to tweak the code as below to see if the value "looks" like a number and, if so, convert to to one for comparison. This works but would introduce the opposite problem if you did actually want to compare the values as strings.

            parseInputValidationAttributes: function (element, valueAccessor) {
                ko.utils.arrayForEach(html5Attributes, function (attr) {
                    if (utils.hasAttribute(element, attr)) {
                        var p = element.getAttribute(attr);
                        // see if the parameter could be converted to a number
                        if ($.isNumeric(p)) { p = parseFloat(p); };
                        ko.validation.addRule(valueAccessor(), {
                            rule: attr,
                            // also tweaked the line below to allow 0 as a value
                            params: p === undefined ? true : p
                        });
                    }
                });
            }

Rerun validation when selected item changes

I've set up some chained validations on an observable property that use different validation metrics based on the selected item in a combobox. I've modified the Fiddle example to demonstrate this behavior - http://jsfiddle.net/dhm116/7GsWY/ .

In the Fiddle, the password length requirement changes based on which subscription type is selected. If the validation rule passes after the selected combobox item changes, it will behave properly, however if multiple validation rules fail, it will not display the message of the relavent rule properly. I cannot find a way to display the proper message from the rule that matches after the subscription type is changed.

At the moment, the user has to change the text in the password box for the correct validation message to appear, it will not happen automatically when the subscription type changes.

I've tried using ko.validation.validateObservable in the change event on the combobox, but that did not appear to do anything useful. Do you have any suggestions as to how to address this issue?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.