Knockout validation

6,076 views
5,571 views

Published on

Published in: Technology, Art & Photos
0 Comments
2 Likes
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total views
6,076
On SlideShare
0
From Embeds
0
Number of Embeds
34
Actions
Shares
0
Downloads
44
Comments
0
Likes
2
Embeds 0
No embeds

No notes for slide

Knockout validation

  1. 1. JASON
  2. 2. Knockout Validation  A KnockoutJS Plugin for model and property validation
  3. 3. Native Rules  Required  ko.observable().extend({ required: true });  Min  ko.observable().extend({ min: 2 });  Max:  ko.observable().extend({ max: 99 });  MinLength  ko.observable().extend({ minLength: 3 });  MaxLength:  ko.observable().extend({ maxLength: 12 });  Pattern:  ko.observable().extend({ pattern: '^[a-z0-9].$' });
  4. 4. Native Rules  Date  ko.observable().extend({ date: true });  Email:  ko.observable().extend({ email: true });  Equal:  ko.observable().extend({ equal: 2 });  Not Equal:  ko.observable().extend({ notEqual: 2 });  Number:  ko.observable().extend({ number: true });
  5. 5. Use var viewModel = { phone: ko.observable().extend({ required: true }); submit: function () { if (viewModel.errors().length == 0) { alert('Thank you.'); } else { viewModel.errors.showAllMessages(); } } }; viewModel.errors = ko.validation.group(viewModel); ko.validation.configure(); ko.applyBindingsWithValidation(viewModel);
  6. 6. Custom Validation Rules ko.validation.rules['mustEqual'] = { validator: function (val, otherVal) { return val === otherVal; }, message: 'The field must equal {0}' }; ko.validation.registerExtenders(); var myCustomObj = ko.observable().extend({ mustEqual: 5 });
  7. 7. Custom Message Template <script id="customMessageTemplate" type="text/html"> <em class="customMessage" data-bind='validationMessage: field'></em> </script> <div data-bind='validationOptions: { messageTemplate: "customMessageTemplate" }'> …… </div>
  8. 8. Configuration Option Default insertMessages true decorateElement false errorMessageClass ‘validationMessage’ errorElementClass ‘validationElement’ errorsAsTitle true parseInputAttributes false errorClass null ko.validation.configure({ insertMessages: true, errorsAsTitle:true, errorElementClass: “errorClass", errorMessageClass: “errorMessageClass", decorateElement:true });

×