Yupinator is a powerful and flexible utility for validating query parameters using Yup schemas. Designed for use in frameworks like Next.js, Express, and other Node.js environments, it ensures clean and reliable parameter validation with minimal effort.
- Schema-based Validation: Use Yup schemas to define validation rules.
- Error Handling: Provides detailed error messages for invalid inputs.
- Simple Integration: Works seamlessly with URLSearchParams from new URL(req.url).
Install Yupinator via NPM:
npm install yupinator
The validateQueryParams function extracts query parameters from URLSearchParams and validates them against a Yup schema.
Example:
import { validateQueryParams } from 'yupinator';
import * as Yup from 'yup';
const validationSchema = Yup.object({
first_name: Yup.string().required('First name is required'),
age: Yup.number().positive('Age must be positive').required('Age is required'),
});
async function handleRequest(req: Request) {
const { searchParams } = new URL(req.url);
const { isValid, data, errors } = await validateQueryParams(searchParams, validationSchema);
if (isValid) {
console.log('Validated data:', data);
return new Response('Validation passed!', { status: 200 });
} else {
console.error('Validation errors:', errors);
return new Response(JSON.stringify({ errors }), { status: 400, headers: { 'Content-Type': 'application/json' } });
}
}
validateQueryParams(searchParams: URLSearchParams, schema: Yup.ObjectSchema)
- Parameter: searchParams - Type: URLSearchParams - Description: Extracted from new URL(req.url).
- Parameter: schema - Type: Yup.ObjectSchema - Description: A Yup schema to validate the inputs.
Returns:
- isValid: boolean - Indicates if the validation passed (true) or failed (false).
- data: Record<string, any> - Validated query parameters (only available if isValid is true).
- errors: Record<string, string> - Object containing error messages for each invalid parameter (if invalid).
import { validateQueryParams } from 'yupinator';
import * as Yup from 'yup';
const schema = Yup.object({
first_name: Yup.string().required('First name is required'),
last_name: Yup.string().required('Last name is required'),
});
const { searchParams } = new URL('http://example.com?first_name=John&last_name=Doe');
validateQueryParams(searchParams, schema).then(({ isValid, data, errors }) => {
if (isValid) {
console.log('Validated data:', data);
} else {
console.error('Validation errors:', errors);
}
});
import { NextRequest } from 'next/server';
import { validateQueryParams } from 'yupinator';
import * as Yup from 'yup';
export async function GET(req: NextRequest) {
const schema = Yup.object({
first_name: Yup.string().required('First name is required'),
age: Yup.number().positive('Age must be positive').required('Age is required'),
});
const { searchParams } = new URL(req.url);
const { isValid, data, errors } = await validateQueryParams(searchParams, schema);
if (!isValid) {
return new Response(JSON.stringify({ errors }), { status: 400, headers: { 'Content-Type': 'application/json' } });
}
return new Response(JSON.stringify({ message: 'Success', data }), {
status: 200,
headers: { 'Content-Type': 'application/json' },
});
}
import { validateQueryParams } from 'yupinator';
import * as Yup from 'yup';
const schema = Yup.object({
email: Yup.string().email('Invalid email address').required('Email is required'),
age: Yup.number().min(18, 'You must be at least 18 years old').required('Age is required'),
});
const { searchParams } = new URL('http://example.com?email=invalid-email');
validateQueryParams(searchParams, schema).then(({ isValid, data, errors }) => {
if (!isValid) {
console.log('Errors:', errors);
}
});
URLSearchParams is a native browser and Node.js API that makes parsing query strings clean and consistent. It integrates seamlessly with new URL(req.url) in server-side frameworks like Next.js, Express, and more.
When validation fails:
- The isValid field will be false.
- The errors field will contain an object mapping invalid parameters to their respective error messages.
While Yupinator is optimized for query parameters (URLSearchParams), the core logic can be adapted for any input that maps to a Record<string, any>.
MIT License