File tree Expand file tree Collapse file tree 2 files changed +40
-0
lines changed Expand file tree Collapse file tree 2 files changed +40
-0
lines changed Original file line number Diff line number Diff line change @@ -201,6 +201,33 @@ describe('Reporter', () => {
201
201
expect ( errors [ 0 ] ) . toBe ( message ) ;
202
202
}
203
203
} ) ;
204
+
205
+ it ( 'should report an error when string does not match specified regex' , ( ) => {
206
+ interface S {
207
+ s1 : string ;
208
+ }
209
+ interface T {
210
+ t1 : string ;
211
+ }
212
+
213
+ const REGEX = / ^ [ 0 - 9 ] + $ / ;
214
+ const VALUE = 'aaa' ;
215
+ const schema = createSchema < T , S > ( {
216
+ t1 : {
217
+ fn : value => value . s1 ,
218
+ validation : Validation . string ( ) . regex ( REGEX )
219
+ }
220
+ } ) ;
221
+ const result = morphism ( schema , { s1 : VALUE } ) ;
222
+ const error = new ValidationError ( { targetProperty : 't1' , expect : `value to match pattern: ${ REGEX } ` , value : VALUE } ) ;
223
+ const message = defaultFormatter ( error ) ;
224
+ const errors = reporter . report ( result ) ;
225
+ expect ( errors ) . not . toBeNull ( ) ;
226
+ if ( errors ) {
227
+ expect ( errors . length ) . toEqual ( 1 ) ;
228
+ expect ( errors [ 0 ] ) . toBe ( message ) ;
229
+ }
230
+ } ) ;
204
231
} ) ;
205
232
206
233
describe ( 'number' , ( ) => {
Original file line number Diff line number Diff line change @@ -56,4 +56,17 @@ export class StringValidator extends BaseValidator<string> {
56
56
} ) ;
57
57
return this ;
58
58
}
59
+ regex ( regex : RegExp ) {
60
+ this . addRule ( {
61
+ name : 'regex' ,
62
+ expect : `value to match pattern: ${ regex } ` ,
63
+ test : function ( value ) {
64
+ if ( ! regex . test ( value ) ) {
65
+ throw new ValidatorError ( { value, expect : this . expect } ) ;
66
+ }
67
+ return value ;
68
+ }
69
+ } ) ;
70
+ return this ;
71
+ }
59
72
}
You can’t perform that action at this time.
0 commit comments