Exploring JSON Schema for Form Validation in Web Components
2024-8-14 23:11:55 Author: hackernoon.com(查看原文) 阅读量:5 收藏

In the realm of modern web development, ensuring data integrity and user experience is paramount. JSON Schema has emerged as a powerful tool for validating the structure of JSON data, providing developers with a standardized approach to data validation, documentation, and extensibility. When combined with Web Components, JSON Schema becomes an even more potent solution for form validation, offering a modular, reusable, and maintainable approach to UI development.

This blog post will walk you through the process of integrating JSON Schema validation into a custom Web Component, using a contact form as our example.

Understanding JSON Schema

JSON Schema is a vocabulary that allows you to annotate and validate JSON documents. It serves three primary purposes:

  1. Data Validation: Ensure that JSON data conforms to a defined structure.

  2. Documentation: Provide a clear, standardized way to describe the structure of JSON data.

  3. Extensibility: Allow for the extension of validation rules to accommodate specific requirements.

Common keywords used in JSON Schema include:

  • type: Defines the data type (e.g., string, number).
  • properties: Specifies the expected properties within the JSON object.
  • required: Lists the properties that must be present.
  • enum: Restricts a property to a fixed set of values.

By leveraging these keywords, JSON Schema enhances data quality, improves developer productivity, and facilitates better communication between different parts of a software system.

Web Components: An Overview

Web Components are a suite of technologies that allow developers to create reusable custom elements with encapsulated functionality and styling. These components are ideal for building modular, maintainable UI elements that can be easily integrated into any web application.

Creating a Contact Form Web Component

Contact us Web component:

contact-us-form-validation-with-json-schema

Here is the Sample code representing contact us web component

class ContactUsForm extends HTMLElement {

            template = document.createElement("template");

            constructor() {
                super();
                this.attachShadow({ mode: 'open' });
                this.template.innerHTML = `
                <form id="contact">
                    <fieldset style="display: block;">
                        <legend>Contact Us</legend>
                        <p>
                            <label for="firstname">
                                First Name: 
                            </label>
                            <input type="text" id="firstname" name="firstName">
                        </p>
                        <p>
                            <label for="lastname">
                                Last Name: 
                            </label>
                            <input type="text" id="lastname" name="lastName">
                        </p>
                        <p>
                            <label for="email">
                            Email: 
                            </label>
                            <input type="email" id="email" name="email">
                        </p>
                        <input type="submit">
                    </fieldset>
                </form>
            `;
                this.render();
            }

            render() {
                this.shadowRoot.appendChild(this.template.content.cloneNode(true));
            }
        }

        customElements.define('contact-us-form', ContactUsForm);

Defining the JSON Schema

Below is a JSON Schema tailored for our contact form:

{
  "$schema": "https://json-schema.org/draft/2020-12/schema",
  "$id": "https://spradeep.com/contact-us.schema.json",
  "title": "Contact us",
  "description": "Contact us",
  "type": "object",
  "properties": {
    "firstName": {
      "description": "First name of the user",
      "type": "string",
      "minLength": 3
    },
    "lastName": {
      "description": "Last name of the user",
      "type": "string"
    },
    "email": {
      "description": "Email address of the user",
      "type": "string",
      "pattern": "^\\S+@\\S+\\.\\S+$",
      "minLength": 6,
      "maxLength": 127
    }
  },
  "required": [
    "firstName",
    "email"
  ]
}

Validation of the contact form fields are represented using the keywords required and pattern

Required Validation:

  "required": [ "firstName",  "email" ]

Email input Validation.

"type": "string",
"pattern": "^\\S+@\\S+\\.\\S+$",

Integrating JSON Schema Validation

To incorporate validation, we’ll utilize Ajv, a widely used JSON Schema validator:

Ajv generates code to turn JSON Schemas into super-fast validation functions that are efficient for v8 optimization.

  • Include Ajv in your project:

<script src="https://cdnjs.cloudflare.com/ajax/libs/ajv/8.17.1/ajv2020.bundle.js"
        integrity="sha512-sHey9yWVIu+Vv88EJmYFuV/L+6YTrw4ucDBFTdsQNuROSvUFXQWOFCnEskKWHs1Zfrg7StVJoOMbIP7d26iosw=="
        crossorigin="anonymous" referrerpolicy="no-referrer"></script>
  • Initialize Ajv and compile the schema:
//Initialize AJV
var Ajv = window.ajv2020;
var ajv = new Ajv({ allErrors: true, verbose: true, strict: false });

//Pass contactUs JSON schema to AJV 

const contactUsSchema = {
                    "$schema": "https://json-schema.org/draft/2020-12/schema",
                    "$id": "https://spradeep.com/contact-us.schema.json",
                    "title": "Contact us",
                    "description": "Contact us",
                    "type": "object",
                    "properties": {
                        "firstName": {
                            "description": "First name of the user",
                            "type": "string",
                            "minLength": 3,
                        },
                        "lastName": {
                            "description": "Last name of the user",
                            "type": "string"
                        },
                        "email": {
                            "description": "Email address of the user",
                            "type": "string",
                            "pattern": "^\\S+@\\S+\\.\\S+$",
                            "minLength": 6,
                            "maxLength": 127
                        }
                    },
                    "required": ["firstName", "email"]
                };
                //Reference Contact us JSON schema to be used for validation of contact us data
                const validate = ajv.compile(contactUsSchema)
  • Validate form data upon submission:

var formData = new FormData(form);
//call validate function returned by AJV
const valid = validate(formData);
//valid is an object that returns if data is valid as per schema and errors

Here is how the errors are shown, when user tries to provide an invalid input.

errors-shown-after-validating-form-with-json-schema

Benefits and Considerations

  • Separation of Concerns: JSON Schema separates validation logic from the UI, making your code more maintainable.
  • Reusability: Schemas can be reused across different parts of your application, promoting consistency.
  • Documentation: Schemas serve as living documentation, providing a clear specification of your data structures.
  • Performance: While client-side validation is powerful, be mindful of the impact on performance, especially with large forms or complex schemas.

Conclusion

Integrating JSON Schema with Web Components offers a robust solution for form validation in modern web applications. This approach not only improves code maintainability and enhances user experience but also lays a strong foundation for building complex, data-driven forms.

By combining these two technologies, developers can create modular, reusable components that ensure data integrity and streamline the development process.

Here is the reference code to try on your own.

More references to learn more about JSON schema https://json-schema.org/


文章来源: https://hackernoon.com/exploring-json-schema-for-form-validation-in-web-components?source=rss
如有侵权请联系:admin#unsafe.sh