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?
- The
agestring'25'is cast to the number25by thenumbertype handler. - The
usernamestring' alex 'is transformed by thestringtype handler to'alex'(it gets trimmed). - Since there are no validation errors, the
errorsobject will be empty. - The
validatedObjectwill contain the clean, cast, and transformed data.