Reputation: 559
I am using knockout.js in my ASP.NET MVC project. I figured out how to display a form, serialise a JSON object, and display data with the help of following link: How to use knockout.js with ASP.NET MVC ViewModels?
But I am not able to figure out how to validate the form. What is the best solution to validate the form?
Upvotes: 27
Views: 25108
Reputation: 2228
Although the answer is accepted, but I would like to share my approach. I prefer to combine jquery with knockout.js and apply the jQuery Validation plugin that suits very well for unobtrusive client-side form validation. It works prior to the form submission and accepts the form as an input parameter. Something like this:
function ViewModel() {
var self = this;
self.firstName = ko.observable();
self.lastName = ko.observable();
self.email = ko.observable();
self.validate = function(form) {
return $(form).validate();
};
};
var viewModel = new ViewModel();
ko.applyBindings(viewModel);
The validate() function is called If the validation succeeds, the form will be submitted, otherwise, an error will be displayed.
Upvotes: 3
Reputation: 1637
Try the Knockout.Validation plugin:
https://github.com/Knockout-Contrib/Knockout-Validation
Upvotes: 4
Reputation: 22338
I have used he Knockout.Validation plugin ( https://github.com/Knockout-Contrib/Knockout-Validation ) which has worked well. It uses extenders in Knockout so you can extend the model properties to include rules like required, min, max, or pattern matches. You can also create custom rules. I created one for a url, for example. It has some built in rule for things like email, too. All of this is in the github page in the docs. It has everything you need to get started.
Another option is to use jquery validation, which also works well.
Upvotes: 37