1- import { days , defined , future , gt , gte , includes , inList , lt , lte , past , Struct , required , valid , validate , notEmpty } from '../../src' ;
1+ import {
2+ constraint ,
3+ days ,
4+ defined ,
5+ future ,
6+ gt ,
7+ gte ,
8+ includes ,
9+ inList ,
10+ isValue ,
11+ lt ,
12+ lte ,
13+ notEmpty ,
14+ past ,
15+ required ,
16+ Struct ,
17+ Text ,
18+ valid ,
19+ validate ,
20+ } from '../../src' ;
221import '@thisisagile/easy-test' ;
3- import { Language } from '../ref' ;
22+ import { Age , Language } from '../ref' ;
423
524describe ( 'Constraints' , ( ) => {
625 class Tester extends Struct {
@@ -19,7 +38,15 @@ describe('Constraints', () => {
1938 }
2039
2140 test ( 'All constraints succeed.' , ( ) => {
22- const t = new Tester ( { first : 'Sander' , one : 6 , two : 6 , past : days . yesterday ( ) , future : days . tomorrow ( ) , language : 'java' , title : 'Prof.' } ) ;
41+ const t = new Tester ( {
42+ first : 'Sander' ,
43+ one : 6 ,
44+ two : 6 ,
45+ past : days . yesterday ( ) ,
46+ future : days . tomorrow ( ) ,
47+ language : 'java' ,
48+ title : 'Prof.' ,
49+ } ) ;
2350 const r = validate ( t ) ;
2451 expect ( r ) . toBeValid ( ) ;
2552 } ) ;
@@ -30,3 +57,29 @@ describe('Constraints', () => {
3057 expect ( r ) . not . toBeValid ( ) ;
3158 } ) ;
3259} ) ;
60+
61+ const is42 = ( message ?: Text ) : PropertyDecorator => constraint ( v => v === 42 , message ?? 'Property {property} should have value \'42\' instead of \'{actual}\'.' ) ;
62+
63+ class Person extends Struct {
64+ @valid ( ) readonly age : Age = new Age ( this . state . age ) ;
65+ @is42 ( ) readonly realAge : number = this . state . age ;
66+ }
67+
68+ describe ( 'Custom constraints' , ( ) => {
69+
70+ test ( 'test age' , ( ) => {
71+ expect ( isValue ( new Age ( 42 ) ) ) . toBeTruthy ( ) ;
72+ expect ( validate ( new Age ( 42 ) ) ) . toBeValid ( ) ;
73+ expect ( validate ( new Age ( 142 ) ) ) . not . toBeValid ( ) ;
74+ } ) ;
75+
76+ test ( 'test person' , ( ) => {
77+ expect ( validate ( new Person ( { age : 42 } ) ) ) . toBeValid ( ) ;
78+ expect ( validate ( new Person ( { age : 142 } ) ) ) . not . toBeValid ( ) ;
79+ } ) ;
80+
81+ test ( 'test custom validation' , ( ) => {
82+ const res = validate ( new Person ( { age : 142 } ) ) ;
83+ expect ( res . results ) . toHaveLength ( 2 ) ;
84+ } ) ;
85+ } ) ;
0 commit comments