Standalone Validator Usage #1668
-
Hi, We are making standalone usage of validator as follow:
Now, at the time of validation, the code goes like const profileValidator = new ProfileValidator();
profileValidator.data = params;
await validator.validate(profileValidator); Please note the line The current default validator class does not have a data attribute, nor does it accept it through the constructor. If it were accepting data through the constructor, like this import { HttpContextContract } from '@ioc:Adonis/Core/HttpContext';
import { schema, rules } from '@ioc:Adonis/Core/Validator';
export default class ProfileValidator {
constructor(private ctx: HttpContextContract, public data: {}) {}
public schema = schema.create({
});
public cacheKey = this.ctx.routeKey;
public messages = {};
} the above code could have been simplified as const profileValidator = new ProfileValidator(null, params);
await validator.validate(profileValidator); I know, the current constructor accepts ctx as the parameter, which can again be used for cacheKey. My query is: Another alternate usage could be const profileValidator = new ProfileValidator();
await validator.validate({ data: params, ...profileValidator} ); Is there any other better approach? |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 6 replies
-
Hi, @thetutlage Please help with your thoughts whenever you get time. |
Beta Was this translation helpful? Give feedback.
-
What you are looking for is a validator that is not hardly tied with HTTP requests only. In this case, I will recommend getting rid of import { schema } from '@ioc:Adonis/Core/Validator'
export default class ProfileValidator {
constructor (public data: any) {
}
public schema = schema.create({
})
public messages = {}
} Now, you can use it as follows import { validator } from '@ioc:Adonis/Core/Validator'
validator.validate(new ProfileValidator({})) And during HTTP requests request.validate(new ProfileValidator(request.all())) |
Beta Was this translation helpful? Give feedback.
What you are looking for is a validator that is not hardly tied with HTTP requests only. In this case, I will recommend getting rid of
ctx
altogether (since outside HTTP requests, you will not have access to it) and accept just the data inside the constructor.Now, you can use it as follows
And during HTTP requests