Monday, June 10, 2019

how to create a Knockout JS custom handler for duplicate email validation?

In the current Knockout JS web application, we want to validate the user input in the email field to make sure the input does not exist in our system.

i implemented the business logic in the textbox blur event. it means that the validation call to the back end when the cursor leaves the textbox.

here is snippet of code to implement binding handler in Knockout JS

ko.bindingHandlers.validateEmail = {
    init: function (element, valueAccessor, allBindingsAccessor, data, context) {
        var options = allBindingsAccessor().validateEmailParams || {};
        $(element).blur(function () {
            var customerId = options.customerID();
            var email = options.emailAddress();
            var value = valueAccessor();
            var dataModel = sci.dataModel;
            dataModel.CheckDuplicateEmail(customerId, email).then(function (response) {
                if (response != null) {
                    if (response) {
                        valueAccessor().setError(loc.DuplicateEmailMySubaruAccount);
                    }
                }
            });
        });

        return ko.bindingHandlers.value.init.apply(this, arguments);
    },
    update: ko.bindingHandlers.value.update
};

HTML Code

 <input autocomplete="off" id="email" class="form-control" type="text" data-bind="value: email,validationElement:email, validateEmail:email, validateEmailParams:{emailAddress: email, customerID:accountNumber}, attr: { placeholder: loc.Email }" />

No comments:

Post a Comment