articles

Home / DeveloperSection / Articles / Form validation and request submission in knockout js

Form validation and request submission in knockout js

Form validation and request submission in knockout js

Ravi Vishwakarma 269 29-May-2024

To validate form inputs using Knockout.js, you can use the knockout-validation plugin, which provides a set of validation rules and utilities to ensure that your form inputs are valid before submission. Below are the steps to integrate validation into the Knockout.js example:

Step 1: Setting Up Your HTML Form

First, add the knockout-validation plugin to your HTML file along with Knockout.js:

<!doctype html>
<html lang="en">
<head>
    <!-- Meta tags for character set and viewport configuration -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <!-- Title of the webpage -->
    <title>Bootstrap demo</title>
    <!-- Link to Bootstrap CSS for styling -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet"
        integrity="sha384-QWTKZyjpPEjISv5WaRU9OFeRpok6YctnYmDr5pNlyT2bRjXh0JMhjY6hW+ALEwIH" crossorigin="anonymous">
    <!-- Link to Knockout.js library for MVVM pattern support -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.5.1/knockout-latest.min.js"
        integrity="sha512-vs7+jbztHoMto5Yd/yinM4/y2DOkPLt0fATcN+j+G4ANY2z4faIzZIOMkpBmWdcxt+596FemCh9M18NUJTZwvw=="
        crossorigin="anonymous" referrerpolicy="no-referrer"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/knockout-validation/2.0.4/knockout.validation.min.js"
        integrity="sha512-b99MDNv5TqiZtPKH2UeHzDAVydmgrOJEPtaPPEF8AgV86eYyqINFI/K7/7f0+R4WNTAVv8KvvpjwfOYHv5rd5g=="
        crossorigin="anonymous" referrerpolicy="no-referrer"></script>
</head>
<!-- Container class for Bootstrap styling -->
<body class="container">
    <div class="my-4">
        <h5><strong>Validation Form</strong></h5>
        <hr />
        <form class="row g-3" data-bind="submit: submitForm">
            <div class="col-12  col-lg-6">
                <label class="form-label fw-bold" for="name">Name</label>
                <input class="form-control" type="text" id="name" data-bind="value: name, valueUpdate: 'input'" />
            </div>
            <div class="col-12 col-lg-6">
                <label class="form-label fw-bold" for="email">Email</label>
                <input class="form-control" type="email" id="email" data-bind="value: email, valueUpdate: 'input'" />
            </div>
            <div class="col-12">
                <label class="form-label fw-bold" for="Country">Country</label>
                <select class="form-select"
                    data-bind="options: CountryList, value: Country, optionsCaption:'Choose your country ...'"></select>
            </div>
            <div class="col-12">
                <label class="form-label fw-bold" for="PhoneNumber">PhoneNumber</label>
                <input class="form-control" type="number" id="PhoneNumber"
                    data-bind="value: PhoneNumber, valueUpdate: 'input'" />
            </div>
            <div class="col-12">
                <label class="form-label fw-bold" for="Address">Address</label>
                <textarea class="form-control" id="Address" data-bind="value: Address, valueUpdate: 'input'"></textarea>
            </div>
            <div class="col-12">
                <button class="btn btn-primary" type="submit">Submit</button>
            </div>
        </form>
    </div>
    <script src="validation.js" type="text/javascript"></script>
</body>
</html>

Step 2: Create the Knockout ViewModel

Create a ViewModel in a JavaScript file (e.g., validation.js) to manage form data and validation logic.

// Initialize Knockout validation
ko.validation.init({
    registerExtenders: true, // Register custom validation rules
    messagesOnModified: true, // Show validation messages as soon as a field is modified
    insertMessages: true, // Insert validation messages next to the input elements
    parseInputAttributes: true, // Parse HTML5 input attributes for validation rules
    errorClass: 'text-danger fw-semibold', // CSS class for validation error messages
    messageTemplate: null // Use default message template
}, true);

// Define the ViewModel
function AppViewModel() {
    var self = this;

    // Define observables for form fields with validation rules
    self.name = ko.observable("").extend({
        required: { message: "Name is required." },
        minLength: { params: 2, message: "Name must be at least 2 characters." },
        maxLength: { params: 25, message: "Name must be at most 25 characters." }
    });

    self.email = ko.observable("").extend({
        required: { message: "Email is required." },
        email: { message: "Invalid email address." }
    });

    self.PhoneNumber = ko.observable().extend({
        required: { message: "Phone Number is required." },
        pattern: { params: '^[0-9]{8,}$', message: 'Phone Number does not match the pattern' }
    });

    self.CountryList = ko.observableArray(['Morocco', 'India', 'USA']);

    self.Country = ko.observable().extend({
        required: { message: "Country is required." }
    });

    self.Address = ko.observable().extend({
        required: { message: "Address is required." }
    });

    // Define the submit function
    self.submitForm = function () {
        // Check if the form is valid
        if (self.errors().length === 0) {
            // Gather form data
            var formData = {
                name: self.name(),
                email: self.email(),
                phone_number: self.PhoneNumber(),
                country: self.Country(),
                address: self.Address(),
            };

            // Display form data
            window.alert(formData);

            // Log the form data (or send it to the server)
            console.log("Form submitted with:", formData);
        } else {
            // Show validation errors
            self.errors.showAllMessages();
        }

        // Prevent actual form submission
        return false;
    };

    // Initialize validation
    self.errors = ko.validation.group(self);
}

Step 3: Applying Knockout Bindings

In your HTML file, ensure that the Knockout bindings are applied when the document is ready.

// Apply bindings
ko.applyBindings(new AppViewModel());

Explanation

  1. HTML Form: The form contains input fields for name and email, each bound to observables in the ViewModel using the data-bind attribute. Error messages are conditionally displayed using visible binding.
  2. ViewModel:
    • Observables: name and email hold the form data, while nameError and emailError hold validation error messages.
    • Validation: The validateForm function checks if the form fields are filled out correctly and sets error messages if not.
    • Submit Handler: The submitForm function validates the form and, if valid, logs the form data (simulating an AJAX request).
  3. Binding Application: The ko.applyBindings function binds the ViewModel to the form when the DOM content is loaded.

This setup provides a basic framework for form validation and submission in a Knockout.js application. You can extend this by adding more fields, custom validation rules, or real AJAX requests for form submission.

Form validation and request submission in knockout js

Thanks for reading.

Also read: Retrieving and displaying data from a RESTful API in Knockout JS


Ravi Vishwakarma is a dedicated Software Developer with a passion for crafting efficient and innovative solutions. With a keen eye for detail and years of experience, he excels in developing robust software systems that meet client needs. His expertise spans across multiple programming languages and technologies, making him a valuable asset in any software development project.

Leave Comment

Comments

Liked By