Different validator when updating and creating #2515
-
Hello, I have a table with user. When a new user is created, we need the email and the password. When the user updates his profile, other data can be provided, and email and password become optional. To achieve this, do I have to create a new validator or adonis provide a way to handle POST and PATCH ? |
Beta Was this translation helpful? Give feedback.
Replies: 3 comments 2 replies
-
You can create a single validator class and dynamically switch the schema depending on whether it’s a PATCH or a POST. To me this feels like over-engineering, I would just create two separate validators. |
Beta Was this translation helpful? Give feedback.
-
Go with multiple validators. |
Beta Was this translation helpful? Give feedback.
-
I made an extensible solution for this using Class-based Validators. Here is the code for the base import Logger from '@ioc:Adonis/Core/Logger';
import { validator, ParsedTypedSchema } from '@ioc:Adonis/Core/Validator';
export default abstract class Validator {
/**
* Object for schemas.
* Each key in object will correspong to a type of validation.
* Each values will be a valid Adonis schema, made using schema.create
*/
protected abstract schemas(type: string): ParsedTypedSchema<any>;
/**
* Object of error message objects used to pass custom error messages.
* Each key will correspond to a valid validation type defined in schemas
*/
protected errorMessages = {};
/**
* Cache key, to be used if validator schema caching is needed.
* Refer https://preview.adonisjs.com/guides/validator/schema-caching
*/
protected cacheKey: string;
public async fire(data: { [key: string]: any }, type: string): Promise<any> {
return validator.validate({
schema: this.schemas(type),
data,
...(this.errorMessages[type] ? { messages: this.errorMessages[type] } : {}),
...(this.cacheKey ? { cacheKey: this.cacheKey } : {}),
});
}
} And here is the import { rules, schema } from '@ioc:Adonis/Core/Validator';
import Validator from 'App/Validators/Validator';
class UserValidator extends Validator {
protected schemas(type: string) {
switch (type) {
case 'create':
return schema.create({
email: schema.string.optional({}, [rules.email()]),
password: schema.string({}, [rules.confirmed(), rules.minLength(8)]),
name: schema.string(),
// ...Other rules
});
case 'update':
return schema.create({
name: schema.string.optional(),
// ...Other rules
});
default:
return schema.create({});
}
}
}
export default new UserValidator(); Now the service / controller methods just have to call |
Beta Was this translation helpful? Give feedback.
Go with multiple validators.