Knockout check - do not check input when empty + evaluate when sending

check this script:

http://jsfiddle.net/bhzrw01s/

I tried to do 2 things:

First: Do not check when the field is empty. I know there is only one option ... but is there something simpler?

Secondly: I need to run something to check when I click on submit (if you check my fiddle, error messages will appear, but don’t apply 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>
+4
source share
1 answer

90% , . - , , . ( ), . , , , .

http://jsfiddle.net/k08m4dfx/

    self.login = function (e) {
        if (self.errors().length > 0) {
            self.errors.showAllMessages(true);
            this.errors().forEach(function(data) {
               alert(data);
            });
        }
    }

- , , isModified, . , .

http://jsfiddle.net/zd97gjg4/

    ko.extenders.deferValidation = function (target, option) {
        if (option) {
            target.subscribe(function(){
                target.isModified(false);
            });
        }

        return target;
    };

    self.userName = ko.observable().extend({
        required: {message: 'User name is required' },
        deferValidation: true
    });

    self.password = ko.observable().extend({
        required: {message: "Password is required" },
        deferValidation: true
    });
+6

All Articles