The knockout JS is one of the biggest change ever introduced in Magento 2 frontend which can be a little hard but it comes out as a really useful tool. Basically, Knockout JS is nothing but one kind of Javascript library that uses the MVVM pattern to bind data to certain DOM elements. In your Magento source code, we usually define a View-Model and a Template and the data bound to the Magento 2 view-model which means whenever any data changes happen to view-model changes, it reflects the template too.
Many developers new to Magento 2 thinks that Knockout JS is only used at checkout but In reality, Knockout JS can be used anywhere within the frontend even in creating your color picker, image viewer or whatever. But before we move on to anything else let’s first start with implementing our own Custom Form Validation using knockout JS in Magento 2.
Consider a situation, where you have an Extension that provides a custom form on checkout and we needed to validate on the place order button at that time we need to restrict the user from moving further and validate that all required form fields is completed or not? If yes, then the only user is allowed to place an order.
Here is a small piece of code to do the same.
First, we need to create “checkout_index_index.xml” inside our layout folder.

In the above code, we just put a field in checkout before payment list.
Now we have to define our “custom-checkout-form.js” at this location.
app\code\Vendor\Extension\view\frontend\web\js\modal\checkout\custom-checkout-form.js and add this code to the file:

In last step, we need to create one more “custom-checkout-form.js” file inside our custom extension checkout folder.

That’s it you are done! You have successfully placed a field validation in checkout and restrict user from placing an Order. Also, you are free to play and manipulate this according to your need for adding one or more elements to the grid.
Let us know if you are facing an issue while implementing using this code by commenting below.
Happy knocking!

Click to rate this post!
[Total: 22 Average: 4.5]