quirky purple
quirky purple

Reputation: 2219

Any way to display type of error in knockout js validation?

My example is a form with 3 input fields: Name, email1 and email2. I created a custom validator to throw an error when both email fields are empty, but valid when at least one has been given a value. I then have a span that displays an error when this condition is not met.

<span data-bind='if:errors()>0'>One e-mail required</span>

However, if the user were to leave Name empty, it would also throw the validation error and this span would appear. So is there a way to tell what kind of error it is and apply that to my span conditional?

excerpt from Model:

var viewModel = (function () {
    var name = ko.observable().extend({ required: { message: "*" } });
    var email1 = ko.observable();
    var email2 = ko.observable();
    var atLeastOneEmail = ko.computed(function () {
        var email1 = email1(), email2 = email2();
        return !ko.validation.rules.required.validator(email1, true) &&
            !ko.validation.rules.required.validator(email2, true);
    });
    email1.extend({ required: { onlyIf: atLeastOneEmail, message: "*" } });
    email2.extend({ required: { onlyIf: atLeastOneEmail, message: "*" } });

    var errors = ko.validation.group([name, email1, email2]);
});

Upvotes: 0

Views: 471

Answers (1)

CrimsonChris
CrimsonChris

Reputation: 4651

Use different validation groups.

var viewModel = function () {
    var nameErrors = ko.validation.group([name]),
        emailErrors = ko.validation.group([email1, email2]);
};

<span data-bind="if: nameErrors() > 0">Name required</span>
<span data-bind="if: emailErrors() > 0">One e-mail required</span>

Upvotes: 2

Related Questions