Get started with z-schema CDN

MIT licensed

Z-Schema is a lightweight library for validating JSON Schema against JSON data.

Tags:
  • JSON
  • Schema
  • Validator

Stable version

Copied!

How to start using z-schema CDN


<!DOCTYPE html>
<html>
<head>
    <title>Get started with z-schema CDN - cdnhub.io</title>
    <script src="https://cdn.cdnhub.io/z-schema/6.0.1/ZSchema-browser-min.js"></script>
    <style>
        .error {
            color: red;
        }
    </style>
</head>
<body>
    <form id="myForm">
        <label for="name">Name:</label>
        <input type="text" id="name" name="name" required>
        <span class="error" id="nameError"></span>

        <label for="email">Email:</label>
        <input type="email" id="email" name="email" required>
        <span class="error" id="emailError"></span>

        <button type="submit">Submit</button>
    </form>

    <script>
        const form = document.getElementById('myForm');
        const nameInput = document.getElementById('name');
        const nameError = document.getElementById('nameError');
        const emailInput = document.getElementById('email');
        const emailError = document.getElementById('emailError');

        form.addEventListener('submit', async (event) => {
            event.preventDefault();

            const schema = {
                "$schema": "http://json-schema.org/draft-07/schema#",
                "type": "object",
                "properties": {
                    "name": {
                        "type": "string",
                        "minLength": 1
                    },
                    "email": {
                        "type": "string",
                        "format": "email"
                    }
                },
                "required": ["name", "email"]
            };

            const result = await ZSchema.validate(form, schema);

            if (result.errors.length > 0) {
                result.errors.forEach((error) => {
                    const errorElement = document.createElement('span');
                    errorElement.textContent = error.message;
                    errorElement.className = 'error';
                    errorElement.id = `error-${error.path.join('-')}`;
                    const input = document.querySelector(`input[name="${error.path[0]}"]`);
                    input.parentNode.insertBefore(errorElement, input.nextSibling);
                });
                return;
            }

            // Form is valid, submit to the server or perform other actions
            console.log('Form is valid');
        });
    </script>
</body>
</html>
Copied!
Copied!
Copied!
Copied!
Copied!

All versions