1
+ /**
2
+ * Copyright since 2020 by Ortus Solutions, Corp
3
+ * www.ortussolutions.com
4
+ * ---
5
+ * This validator checks the database according to validation data for field uniqueness
6
+ * - table : The table name to seek
7
+ * - column : The column to evaluate for uniqueness or defaults to the name of the field
8
+ */
9
+ component accessors = " true" singleton {
10
+
11
+ property name = " name" ;
12
+
13
+ /**
14
+ * Constructor
15
+ */
16
+ UniqueValidator function init (){
17
+ variables .name = " Unique" ;
18
+ return this ;
19
+ }
20
+
21
+ /**
22
+ * Will check if an incoming value validates
23
+ *
24
+ * @validationResult The result object of the validation
25
+ * @target The target object to validate on
26
+ * @field The field on the target object to validate on
27
+ * @targetValue The target value to validate
28
+ * @validationData The validation data the validator was created with
29
+ */
30
+ boolean function validate (
31
+ required any validationResult ,
32
+ required any target ,
33
+ required string field ,
34
+ any targetValue ,
35
+ any validationData
36
+ ){
37
+ // Default the target column
38
+ var targetColumn = ( isNull ( arguments .validationData .column ) ? arguments .field : arguments .validationData .column );
39
+ // Query it
40
+ var exists = queryExecute (
41
+ " SELECT 1 FROM #arguments .validationData .table # WHERE #targetColumn # = ?" ,
42
+ [ arguments .targetValue ]
43
+ ).recordCount > 0 ;
44
+
45
+ if ( ! exists ) {
46
+ return true ;
47
+ }
48
+
49
+ validationResult .addError (
50
+ validationResult .newError (
51
+ argumentCollection = {
52
+ message : " The #targetColumn # '#arguments .targetValue #' is already in use" ,
53
+ field : arguments .field ,
54
+ validationType : getName (),
55
+ validationData : arguments .validationData
56
+ }
57
+ )
58
+ );
59
+
60
+ return false ;
61
+ }
62
+
63
+ /**
64
+ * Get the name of the validator
65
+ */
66
+ string function getName (){
67
+ return " Unique" ;
68
+ }
69
+
70
+ }
0 commit comments