Crecto
Search…
Validations
Crecto provides validations and constraints which are turned into changeset errors.
Validations are performed without the need to interact with the database.
1
class User < Crecto::Model
2
schema "users" do
3
field :uuid, String
4
field :age, Int32
5
field :name, String
6
field :role, String
7
field :password, String, virtual: true
8
field :password_confirmation, String, virtual: true
9
end
10
11
# Validate that fields arent blank before inserting or updating
12
validate_required :age # or an array [:age, :name]
13
14
# Validate the format of fields using a regex
15
validate_format :name, /^[a-zA-Z]*&/
16
17
# Validate the length of a field
18
validate_length :uuid, is: 36, # min: 36, max: 60
19
20
# Validate the existence of the value of the field in an array
21
validate_inclusion :role, in: ["admin", "user"]
22
23
# Opposite of inclusion
24
validate_exclusion :age, in: Range(0, 20)
25
26
# Generic or custom validation using a proc
27
validate "Passwords must match", ->(user: User) do
28
user.password == user.password_confirmation
29
end
30
31
# Multiple validations
32
validates :name,
33
presence: true,
34
format: {pattern: /^[a-zA-Z]*&/},
35
exclusion: {in: ["foo", "bar"]},
36
length: {min: 2, max: 50}
37
end
Copied!
Copy link