1+ import { ValidationRule } from './ValidationRule' ;
2+
3+ export class NotInRule implements ValidationRule {
4+ private defaultMessage = '' ;
5+ private customMessage ?: string ;
6+
7+ setDefaultMessage ( message : string ) {
8+ this . defaultMessage = message ;
9+ }
10+
11+ setCustomMessage ( message : string ) {
12+ this . customMessage = message ;
13+ }
14+
15+ validate ( value : any , params : any , field : string , inputs : Record < string , any > ) : string | null {
16+ // Skip validation if value is empty
17+ if ( value === undefined || value === null || value === '' ) {
18+ return null ;
19+ }
20+
21+ // Parse parameters
22+ let disallowedValues : string [ ] = [ ] ;
23+ let strictMode = false ;
24+
25+ if ( typeof params === 'string' ) {
26+ // Format: "value1,value2,value3" or "value1,value2,value3,strict"
27+ const paramsArray = params . split ( ',' ) ;
28+
29+ // Check if the last parameter is "strict"
30+ if ( paramsArray . length > 0 && paramsArray [ paramsArray . length - 1 ] . trim ( ) . toLowerCase ( ) === 'strict' ) {
31+ strictMode = true ;
32+ disallowedValues = paramsArray . slice ( 0 , - 1 ) ;
33+ } else {
34+ disallowedValues = paramsArray ;
35+ }
36+ } else if ( Array . isArray ( params ) ) {
37+ // Format: ["value1", "value2", "value3"] or ["value1", "value2", "value3", "strict"]
38+ if ( params . length > 0 && params [ params . length - 1 ] === 'strict' ) {
39+ strictMode = true ;
40+ disallowedValues = params . slice ( 0 , - 1 ) . map ( String ) ;
41+ } else {
42+ disallowedValues = params . map ( String ) ;
43+ }
44+ } else {
45+ return 'Invalid parameters for not_in rule' ;
46+ }
47+
48+ // Check if the value is NOT in the disallowed values list
49+ const isInvalid = strictMode
50+ ? disallowedValues . some ( disallowedValue => disallowedValue === String ( value ) && typeof disallowedValue === typeof value )
51+ : disallowedValues . some ( disallowedValue => String ( disallowedValue ) === String ( value ) ) ;
52+
53+ if ( isInvalid ) {
54+ const msg = this . customMessage || this . defaultMessage ;
55+ return msg
56+ . replace ( '{field}' , field )
57+ . replace ( '{values}' , disallowedValues . join ( ', ' ) ) ;
58+ }
59+
60+ return null ;
61+ }
62+ }
0 commit comments