0
votes

I am using Knockout to validate my page, and everything is working correctly. On input blur, if the required field is empty, the error symbol * is displayed next to the text box. However, I have a span tag at the bottom of the page that I want to display * Required field if and only if a field has the * next to it. My intention was to have the span similar to

<span data-bind="visible: errors().length > 0"> * Required field </span>

The issue is, apparently on page load, the .length of my errors variable from

errors = ko.validation.group({ variables })

evaluates to all my inputs as having errors since they are null or empty on page load. Is there any way to disable this initial validation, but still have it validate on blur? Request any code if necessary, but I did not see that as pertinent at the moment.

1

1 Answers

0
votes

errors() contains all the error messages of your validation group.

Try this:

showRequiredMessage = function() {
    for (i = 0; i < errors().length; i++) {
       if (errors()[i].indexOf("*") > -1 ) {
         return true;
       }
    }
    return false;
}

It checks if any of the error messages contain the *.

<span data-bind="visible: showRequiredMessage()"> * Required field </span>

This is javascript only solution. You can use jQuery too if you prefer.

Edit.

Are you creating the span elements for your validation messages? If so, Try letting the ko-validation do that for you. Example:

var koValidationOptions = {
                    decorateInputElement: true,
                    errorElementClass: 'input-error',
                    insertMessages: true,
                    errorMessageClass: 'field-error'
                };

ko.applyBindingsWithValidation(model, document.getElementById("form1"), koValidationOptions);

Otherwise, if you prefer to add the span manually, you can also test if the user has 'touched' the inputs:

visible: yourProperty.isModified() && !yourProperty.isValid()

Hope it helps