I want to validate displayName with optional and not equal null but it not working. it does not validate @NotEquals(null).
export class UpdateDto implements Partial<UserEntity> {
@ApiProperty()
@IsOptional()
@NotEquals(null)
displayName?: string;
}
this case is pass
input:
{
displayName: null
}
What are your ValidatorOptions https://github.com/typestack/class-validator#passing-options. Maybe you skip missing properties.
I don't set ValidatorOptions. I use the default.
This does not work, because @IsOptional() notices that the value is null and then all other validators (including @NotEquals(null)) are ignored
Checks if given value is empty (=== null, === undefined) and if so, ignores all the validators on the property.
I could also not make this work the other way around: Stackoverflow: "How to allow null, but forbid undefined?"
Recommended
I suggest, that you remove @NotEquals(null) and set skipMissingProperties to true in the validation options
see this Stackblitz example
Alternative
When you want to use the default validation options, you can use ValidateIf to make it work:
export class UpdateDto {
@IsString()
@NotEquals(null)
@ValidateIf((object, value) => value !== undefined)
displayName?: string;
}
This will pass the validation when displayName is undefined or a string, but fail for null.
see this Stackblitz example
Great, it works. 馃槃
Recommended
I suggest, that you remove@NotEquals(null)and setskipMissingPropertiestotruein the validation options
see this Stackblitz exampleAlternative
When you want to use the default validation options, you can use
ValidateIfto make it work:export class UpdateDto { @IsString() @NotEquals(null) @ValidateIf((object, value) => value !== undefined) displayName?: string; }This will pass the validation when
displayNameisundefinedor a string, but fail fornull.see this Stackblitz example
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.
Most helpful comment
Recommended
I suggest, that you remove
@NotEquals(null)and setskipMissingPropertiestotruein the validation optionssee this Stackblitz example
Alternative
When you want to use the default validation options, you can use
ValidateIfto make it work:This will pass the validation when
displayNameisundefinedor a string, but fail fornull.see this Stackblitz example