Skip to content

Getting Started: Your First Schema

Let's start with a common use case: validating a user registration form.

First, import the library's factory function and define the structure of the data you expect.

javascript
import { createSchema } from 'json-rest-schema';

// Define the structure and rules for our user data
const userSchema = createSchema({
  username: { type: 'string', required: true, minLength: 3 },
  email: { type: 'string', required: true },
  age: { type: 'number', min: 18, defaultTo: 18 }
});

Now, let's try to validate an object against this schema.

javascript
// An example input object from a form
const userInput = {
  username: '  alex ', // Includes extra whitespace
  email: 'alex@example.com',
  age: '25' // Note: age is a string here
};

const { validatedObject, errors } = userSchema.create(userInput);

// Check if there were any errors by seeing if the errors object has keys
if (Object.keys(errors).length > 0) {
  console.log("Validation failed!");
  console.log(errors);
} else {
  console.log("Validation successful!");
  console.log(validatedObject);
}

What happens here?

  1. The age string '25' is cast to the number 25 by the number type handler.
  2. The username string ' alex ' is transformed by the string type handler to 'alex' (it gets trimmed).
  3. Since there are no validation errors, the errors object will be empty.
  4. The validatedObject will contain the clean, cast, and transformed data.

GPL-3.0-only