11import "es6-shim" ;
2- import { Contains , Matches , MinLength , ValidateNested , ValidatorConstraint , Validate } from "../../src/decorator/decorators" ;
2+ import { Contains , IsDefined , Matches , MinLength , ValidateNested , ValidatorConstraint , Validate } from "../../src/decorator/decorators" ;
33import { Validator } from "../../src/validation/Validator" ;
4- import { ValidationError , ValidatorConstraintInterface } from "../../src" ;
4+ import { ValidationError , ValidatorConstraintInterface , ValidationOptions , registerDecorator , ValidationArguments } from "../../src" ;
55
66import { should , use } from "chai" ;
77
@@ -937,6 +937,30 @@ describe("validation options", function() {
937937 describe ( "context" , function ( ) {
938938
939939 it ( "should map context" , function ( ) {
940+ function IsLongerThan ( property : string , validationOptions ?: ValidationOptions ) {
941+ return function ( object : Object , propertyName : string ) {
942+ registerDecorator ( {
943+ target : object . constructor ,
944+ propertyName : propertyName ,
945+ options : validationOptions ,
946+ constraints : [ property ] ,
947+ name : "isLongerThan" ,
948+ validator : {
949+ validate ( value : any , args : ValidationArguments ) {
950+ const [ relatedPropertyName ] = args . constraints ;
951+ const relatedValue = ( args . object as any ) [ relatedPropertyName ] ;
952+ if ( relatedValue === undefined || relatedValue === null )
953+ return true ;
954+
955+ return typeof value === "string" &&
956+ typeof relatedValue === "string" &&
957+ value . length > relatedValue . length ;
958+ }
959+ }
960+ } ) ;
961+ } ;
962+ }
963+
940964 class MyClass {
941965 @Contains ( "hello" , {
942966 message : "String is not valid. You string must contain a hello word" ,
@@ -953,14 +977,33 @@ describe("validation options", function() {
953977 }
954978 } )
955979 someOtherProperty : string ;
980+
981+ @IsDefined ( {
982+ context : {
983+ foo : "bar"
984+ }
985+ } )
986+ requiredProperty : string ;
987+
988+ @IsLongerThan ( "lastName" , {
989+ context : { baz : "qux" } ,
990+ message : "$property must be longer then $constraint1. Given value: $value"
991+ } )
992+ firstName : string ;
993+
994+ lastName : string ;
956995 }
957996
958997 const model = new MyClass ( ) ;
959- // model.someProperty = "hell no world";
998+ model . firstName = "Short" ;
999+ model . lastName = "LongerThanFirstName" ;
1000+
9601001 return validator . validate ( model ) . then ( errors => {
961- errors . length . should . be . equal ( 2 ) ;
1002+ errors . length . should . be . equal ( 4 ) ;
9621003 errors [ 0 ] . contexts [ "contains" ] . should . be . eql ( { hi : "there" } ) ;
9631004 errors [ 1 ] . contexts [ "contains" ] . should . be . eql ( { bye : "now" } ) ;
1005+ errors [ 2 ] . contexts [ "isDefined" ] . should . be . eql ( { foo : "bar" } ) ;
1006+ errors [ 3 ] . contexts [ "isLongerThan" ] . should . be . eql ( { baz : "qux" } ) ;
9641007 } ) ;
9651008 } ) ;
9661009
0 commit comments