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

Use @IsOptional() alongside other validators

Open oreofeolurin opened this issue 9 years ago • 5 comments

Currently if I have something like this

export class User{
    @IsOptional()
    @IsString()
    address: string;
}

It throws error if I don't supply a value for address. In actual fact what I want is to be able to validate address to be a string if provided, and if not provided then that's fine.

Removing @IsString() makes it optional once again and works, but then I lose further validation on the property.

oreofeolurin avatar Oct 01 '17 22:10 oreofeolurin

I also experiance this behaviour. The issue is already fixed, but the npm package is not updated https://github.com/pleerock/class-validator/issues/116

vmtzkr avatar Oct 12 '17 14:10 vmtzkr

@oreofeolurin new version released

Diluka avatar Oct 17 '17 05:10 Diluka

@Diluka great would check that out

oreofeolurin avatar Oct 17 '17 15:10 oreofeolurin

I, would go ahead and close this, It has been fixed in v0.7.3

oreofeolurin avatar Oct 17 '17 15:10 oreofeolurin

Is this really fixed? Because I have the same issues now with version 0.73 Consider the following:

export class Language {
  @Matches( PimRegex.nounRequired, { message: PimMessages.required } )
  @MinLength( PimGlobal.min3, { message: minLengthFn } )
  @MaxLength( PimGlobal.max25, { message: maxLengthFn } )
  @IsNotEmpty( { message: PimMessages.required } )
  first: string = ''
  
  @IsOptional()
  @Matches( PimRegex.nounOptional, { message: PimMessages.required } )
  @MinLength( PimGlobal.min3, { message: minLengthFn } )
  @MaxLength( PimGlobal.max25, { message: maxLengthFn } )
  @IsNotEmpty( { message: PimMessages.required } )
  second: string = ''
}

My intention for the second property is not to validate it if there are no changes with the property. However, when first is valid, without interaction with second, the validation error for second is still generated.

My expectation is that second would not be validated until it changes?

Thanks

st-clair-clarke avatar Nov 09 '17 23:11 st-clair-clarke