You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Hi,
is it possible to create a custom validator and use it with validation schema? I don't want to use decorators because I don't control model (it comes from some sdk).
Please consider the following TS example. How should customValidationSchema look to make the custom validator work?
import {ValidatorConstraint, ValidatorConstraintInterface, ValidationArguments, ValidationSchema, registerSchema, validate} from 'class-validator';
@ValidatorConstraint({ name: 'customText', async: false })
export class CustomTextLength implements ValidatorConstraintInterface {
validate(text: string, _args: ValidationArguments) {
return text.length > 1 && text.length < 5;
}
defaultMessage(_args: ValidationArguments) {
return 'Text ($value) is too short or too long!';
}
}
class Model {
name: string;
}
const instance = new Model();
instance.name = 'too-long-name-';
// This schema doesn't work
const customValidationSchema: ValidationSchema = {
name: 'myCustomSchema',
properties: {
name: [{
type: 'customValidation',
constraints: [CustomTextLength]
}],
}
};
registerSchema(customValidationSchema);
validate('myCustomSchema', instance).then(errors => {
if (errors.length > 0) {
console.log('Validation failed: ', errors);
} else {
console.log('Validation succeed.');
}
});
The text was updated successfully, but these errors were encountered:
Hi,
is it possible to create a custom validator and use it with validation schema? I don't want to use decorators because I don't control model (it comes from some sdk).
Please consider the following TS example. How should
customValidationSchema
look to make the custom validator work?The text was updated successfully, but these errors were encountered: