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.
JSON Schema is a vocabulary that allows you to annotate and validate JSON documents. It serves three primary purposes:
Data Validation: Ensure that JSON data conforms to a defined structure.
Documentation: Provide a clear, standardized way to describe the structure of JSON data.
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 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.
Contact us Web component:
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);
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": [ "firstName", "email" ]
"type": "string",
"pattern": "^\\S+@\\S+\\.\\S+$",
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
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.
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/