check this fiddle:
I was trying to do 2 things:
First: Dont validate when the field is empty. I know there is a onlyif option.. but is there something easier?
Second: I need something to run the validation when i click on submit (If you test my fiddle, the error messages will pop, but wont apply the errorClass css)
Thanks :D
css:
input.error {
color: red;
border-color: red;
}
js:
ko.validation.configure({
insertMessages: false,
decorateElement: true,
errorElementClass: 'error',
messagesOnModified: false
});
function SignInViewModel() {
var self = this;
self.userName = ko.observable().extend({
required: true
});
self.password = ko.observable().extend({
required: true
});
self.errors = ko.validation.group(self);
self.login = function (e) {
if (self.errors().length == 0) {
alert('No errors');
} else {
this.errors().forEach(function(data) {
alert(data);
});
//self.errors.showAllMessages(true);
}
}
}
$(function () {
ko.applyBindings(new SignInViewModel());
});
html :
<form>
<fieldset>
<legend>User: <span data-bind='text: errors().length'></span> errors</legend>
<label>User name: <input data-bind='value: userName' type="text"/></label><br/>
<label>Password: <input data-bind='value: password' type="password"/></label>
</fieldset>
<button type="button" data-bind='click: login'>Login</button>
</form>
required
check; it will ONLY fail WHEN the field is empty. So please clarify a bit more :) The second question can be solved through the use of ako.validatedObservable
on your group of fields, and callingisValid()
on it before you submit. This will check if the form was filled correctly, but also show the existing errors and add the error classes and such. See github.com/Knockout-Contrib/Knockout-Validation#getting-started – Parris