DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • MCP Elicitation: Human-in-the-Loop for MCP Servers
  • Datafaker Gen: Leveraging BigQuery Sink on Google Cloud Platform
  • Stop Poisoning Your Models: How I Built a CV Dataset Quality Toolkit I Can Reuse Forever
  • Advanced Auto Loader Patterns for Large-Scale JSON and Semi-Structured Data

Trending

  • Smart Deployment Strategies for Modern Applications
  • One Query, Four GPUs: Tracing a Distributed Training Stall Across Nodes
  • Context Is the New Schema
  • Why SAP S/4HANA Landscape Design Impacts Cloud TCO More Than Compute Costs
  1. DZone
  2. Data Engineering
  3. Data
  4. Exploring JSON Schema for Form Validation in Web Components

Exploring JSON Schema for Form Validation in Web Components

This article shows how to use JSON Schema for validation in a custom Web Component with a contact form, highlighting benefits of reusable UI with integrated validation.

By 
Pradeep kumar Saraswathi user avatar
Pradeep kumar Saraswathi
·
Aug. 14, 24 · Tutorial
Likes (2)
Comment
Save
Tweet
Share
4.9K Views

Join the DZone community and get the full member experience.

Join For Free

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 article 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

Here is a Contact Us Web Component example:

Contact Us web component example

Here is the sample code representing the Contact Us Web Component:

JavaScript
 
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:

JSON
 
{
 "$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"
 ]
}


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

Required Validation

JSON
 
 { "required": [ "firstName",  "email" ]}


Email Input Validation

JSON
 
{"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:

HTML
 
<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:

JavaScript
 
//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:
JavaScript
 
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 the user tries to provide an invalid input.

Errors shown when user tries to provide an invalid input

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.

Data integrity JSON UI Data (computing) Schema

Opinions expressed by DZone contributors are their own.

Related

  • MCP Elicitation: Human-in-the-Loop for MCP Servers
  • Datafaker Gen: Leveraging BigQuery Sink on Google Cloud Platform
  • Stop Poisoning Your Models: How I Built a CV Dataset Quality Toolkit I Can Reuse Forever
  • Advanced Auto Loader Patterns for Large-Scale JSON and Semi-Structured Data

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook