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
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Because the DevOps movement has redefined engineering responsibilities, SREs now have to become stewards of observability strategy.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Related

  • Datafaker Gen: Leveraging BigQuery Sink on Google Cloud Platform
  • Handling Dynamic Data Using Schema Evolution in Delta
  • Automate Azure Databricks Unity Catalog Permissions at the Schema Level
  • How to Enable Azure Databricks Lakehouse Monitoring Through Scripts

Trending

  • How to Merge HTML Documents in Java
  • Understanding the Shift: Why Companies Are Migrating From MongoDB to Aerospike Database?
  • Supervised Fine-Tuning (SFT) on VLMs: From Pre-trained Checkpoints To Tuned Models
  • The Role of AI in Identity and Access Management for Organizations
  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.1K 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

  • Datafaker Gen: Leveraging BigQuery Sink on Google Cloud Platform
  • Handling Dynamic Data Using Schema Evolution in Delta
  • Automate Azure Databricks Unity Catalog Permissions at the Schema Level
  • How to Enable Azure Databricks Lakehouse Monitoring Through Scripts

Partner Resources

×

Comments
Oops! Something Went Wrong

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

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

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 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!