@@ -21,6 +21,7 @@ class Model
2121 const RULE_MIN = 'min ' ;
2222 const RULE_MAX = 'max ' ;
2323 const RULE_MATCH = 'match ' ;
24+ const RULE_UNIQUE = 'unique ' ;
2425
2526 public array $ errors = [];
2627
@@ -62,6 +63,18 @@ public function validate()
6263 if ($ ruleName === self ::RULE_MATCH && $ value !== $ this ->{$ rule ['match ' ]}) {
6364 $ this ->addError ($ attribute , self ::RULE_MATCH , ['match ' => $ rule ['match ' ]]);
6465 }
66+ if ($ ruleName === self ::RULE_UNIQUE ) {
67+ $ className = $ rule ['class ' ];
68+ $ tableName = $ className ::tableName ();
69+ $ db = Application::$ app ->db ;
70+ $ statement = $ db ->prepare ("SELECT * FROM $ tableName WHERE $ attribute = : $ attribute " );
71+ $ statement ->bindValue (": $ attribute " , $ value );
72+ $ statement ->execute ();
73+ $ record = $ statement ->fetchObject ();
74+ if ($ record ) {
75+ $ this ->addError ($ attribute , self ::RULE_UNIQUE );
76+ }
77+ }
6578 }
6679 }
6780 return empty ($ this ->errors );
@@ -75,6 +88,7 @@ public function errorMessages()
7588 self ::RULE_MIN => 'Min length of this field must be {min} ' ,
7689 self ::RULE_MAX => 'Max length of this field must be {max} ' ,
7790 self ::RULE_MATCH => 'This field must be the same as {match} ' ,
91+ self ::RULE_UNIQUE => 'Record with with this {field} already exists ' ,
7892 ];
7993 }
8094
@@ -85,6 +99,7 @@ public function errorMessage($rule)
8599
86100 public function addError (string $ attribute , string $ rule , $ params = [])
87101 {
102+ $ params ['field ' ] ??= $ attribute ;
88103 $ errorMessage = $ this ->errorMessage ($ rule );
89104 foreach ($ params as $ key => $ value ) {
90105 $ errorMessage = str_replace ("{ {$ key }} " , $ value , $ errorMessage );
0 commit comments