Search code examples
validationknockout.jsknockout-validation

knockout validation after input


I have a class:

Model.Feedback.Data = function () {
    var self = this;

    self.Name = ko.observable('').extend({
        pattern: {
            params: /^[A-Za-z]+[A-Za-z\s]*$/,
            message: 'Invalid name'
        }
    });

    self.Email = ko.observable('').extend({     
        pattern: {
            params: /^[a-zA-Z0-9!#$%&'*+/=?^`{|}~]+(?:[\._-][a-zA-Z0-9!#$%&'*+/=?^`{|}~]+)*@(?:[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?\.)+[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?$/,
            message: 'Invalid e-mail'
        },
        maxLength: {
            params: 256,
            message: 'Long email'
        }
    });

    return this;
};

I have an HTML code:

<form class="form-additem-checkin" data-bind="submit: send">
    <!--ko with: Data-->
    <div class="form-additem-group-row">
        <div class="form-additem-group-row__col form-additem-group-row__col_label"><div class="form-additem-group__label">E-mail</div></div>
        <div class="form-additem-group-row__col form-additem-group-row__col_field">
            <input type="text" class="field field_type2 input--full" placeholder="You e-mail" data-bind="textInput: Email" />
            <div class="form-additem-group-row__error" data-bind="validationMessage: Email"></div>
        </div>
    </div>  
    <div class="form-additem-group-row">
        <div class="form-additem-group-row__col form-additem-group-row__col_label"><div class="form-additem-group__label">Name</div></div>
        <div class="form-additem-group-row__col form-additem-group-row__col_field">
            <input type="text" class="field field_type2 input--full" placeholder="You name" data-bind="textInput: Name" />
            <div class="form-additem-group-row__error" data-bind="validationMessage: Name"></div>
        </div>
    </div>
    <!--/ko-->
    <div class="form-additem-auth__button">
        <button type="submit" class="btn btn--green form-additem-button">Send</button>
    </div>
</form>

Now, if you enter test@ a in the email field, you will immediately get an error message.

What can I do to check the field after losing the focus of the field?


Solution

  • Usage of value binding instead textInput seems to resolve it. (Credits: Jason Spake)

    Alternatively you can use hasFocus binding and show the error message once there is no focus. (Not so elegant + message disappears once the input is focussed again.)