Skip to content

No response for Form validation

I tried to do form validation for a custom form through class and data-validation but no response from both methods. May I know what is the correct way to do it?

app/code/MyModule/Knockout/view/frontend/web/js/custom-component.js

define(['jquery', 'uiComponent', 'ko', 'mage/validation'], function ($, Component, ko) {
    'use strict';
    return Component.extend({
        defaults: {
            template: 'MyModule_Knockout/knockout-test'
        },
        initialize: function () {
            console.log("hihi")
            this.customerName = ko.observableArray([]);
            this.customerData = ko.observable('');
            this._super();
        },
        addNewCustomer: function() {
            var newKeywordField = $(this.customerName);
            newKeywordField.validation();
            if(newKeywordField.validation('isValid')) {
                this.customerName.push({name:this.customerData()});
                this.customerData("");
            }
            else {
                alert('no special character!!')
            }

        }
    });
}
);

app/code/MyModule/Knockout/view/frontend/web/template/knockout-test.html

<div class="component-wrapper">
    <div class="field">
        <label class="label" for="email"><span data-bind="i18n: 'New Customer'"></span></label>
        <div class="control" >
            <input name="customername"
                   id="customername"
                   type="text"
                   class="input-text"
                   data-bind='value: customerData'
                   data-validate="{'validate-alphanum':true}"
                   >
        </div>
    </div>
    <div class="primary">
        <button type="button" class="action action-login secondary" data-bind="click: addNewCustomer">
            <span data-bind="i18n: 'Save'"></span>
        </button>
    </div>

<div class="customer-list" style="width: 20%;background: gray;margin-top: 10px;" data-bind="foreach: customerName">
    <li data-bind="text: name"></li>
</div>