class-validator icon indicating copy to clipboard operation
class-validator copied to clipboard

question: validate on insert and on update

Open andreanta opened this issue 8 years ago • 5 comments

I i have to distinguish from insert validation and update validation. For example the IsEmailAlreadyExist custom validator i have to use only if i have to insert a new record and not updating the same. I heve tried to use different groups but i have to decorate every field on my entities.

I have put a ValidateIf with the presence of the ID but is not a clean way.

I'd like to create a custom costraint and a decorator to accomplish that.

TIA Andrea Del Brocco

andreanta avatar Nov 01 '18 15:11 andreanta

Groups like insert and update is the only solution I know 😕

MichalLytek avatar Nov 01 '18 16:11 MichalLytek

Hi @andreanta

Can you please detail your question a little more with a minimal example of what do you want to achieve and why you cannot achieve it.

NoNameProvided avatar Nov 04 '18 21:11 NoNameProvided

Hi, i try to better explain: Usually when you insert an entity you have to do some different validation, for example i have to check if the user exist. I use the example IsEmailAlreadyExist as decorator that check if the email is already used.

When i update the same entity i have to skip this validation or access some other fields inside it to better make a find query (es where id <> xx).

I'll try to use different groups (one for insert one for update) and try to pass different parameter on validation inside the save logic but i have to put group inside every validation property and is too much customization.

Now i'll try to use a validateif to exclude the validation but it does not validate all the filed not only the check .

@ValidatorConstraint({ name: "isEmailAlreadyExist", async: true })
@Injectable()
export class IsEmailAlreadyExist implements ValidatorConstraintInterface {
	constructor(protected readonly anagraficaService: AnagraficaService) {}

	async validate(text: string) {
		const user = await this.anagraficaService.findOne({
			Email: text,
		});
		return !user;
	}
}

andreanta avatar Nov 05 '18 09:11 andreanta

@andreanta Did you resolve this issue?

vlapo avatar Mar 27 '20 20:03 vlapo

This thread has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs.

lock[bot] avatar Apr 25 '20 13:04 lock[bot]