Validation Conditionals
Validations can be made conditional based on some other method call or criteria. The available conditionals are if
, unless
, and on
. With on
a create
or update
life cycle event may be specified.
If
1
2
3
4
5
6
7
8
9
10
11
12
13 | use ORM::ActiveRecord::Model;
class Book is Model {
submethod BUILD {
self.validate: 'title', { :presence, :if => { self.returns-true } }
}
method returns-true { True }
}
my $book = Book.build;
say $book.is-valid;
say $book.errors.title[0];
|
Output
Unless
1
2
3
4
5
6
7
8
9
10
11
12
13 | use ORM::ActiveRecord::Model;
class Book is Model {
submethod BUILD {
self.validate: 'title', { :presence, :unless => { self.returns-false } }
}
method returns-false { False }
}
my $book = Book.build;
say $book.is-valid;
say $book.errors.title[0];
|
Output
On
Create
| use ORM::ActiveRecord::Model;
class User is Model {
submethod BUILD {
self.validate: 'fname', { :presence, on => { :create } }
}
}
my $user = User.create({});
say $user.is-valid;
say $user.errors.fname[0];
|
Output
Update
1
2
3
4
5
6
7
8
9
10
11
12
13
14 | use ORM::ActiveRecord::Model;
class User is Model {
submethod BUILD {
self.validate: 'fname', { :presence, on => { :update } }
}
}
my $user = User.create({});
say $user.is-valid;
$user.update({fname => ''});
say $user.is-valid;
say $user.errors.fname[0];
|
Output
| True
False
must be present
|