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

1
2
False
must be present

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

1
2
False
must be present

On

Create

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
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

1
2
False
must be present

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

1
2
3
True
False
must be present