-
Notifications
You must be signed in to change notification settings - Fork 0
Validators
mike edited this page Apr 26, 2020
·
7 revisions
If you worked with Rails, you should know about validates
method
Sirius has the same concept for validating models.
All Validators classes in Sirius extend base class: Sirius.Validator
and have one property (@msg
) and one method validate(value, attr)
if validate
return false
just set @msg
with an error.
Sirius in the current moment has the next validators:
- length
- exclusion
- inclusion
- format
- numericality
- presence
See the example
class Model extends Sirius.BaseModel
@attrs: ["id", "title", "description"]
@validate :
id:
presence: true,
numericality: only_integers: true
inclusion: within: [1..10]
validate_with: (value) ->
#@msg = ....
true
title:
presence: true
format: with: /^[A-Z].+/
length: min: 3, max: 7
exclusion: within: ["Title"]
description:
custom: true
validate_with: (desc) ->
if desc == "foo"
true
else
@msg = "Description must be foo"
false
First of all, you need to define own validator class:
class UrlValidator extends Sirius.Validator
validate: (url, attrs) ->
re = /^(http[s]?:\/\/){0,1}(www\.){0,1}[a-zA-Z0-9\.\-]+\.[a-zA-Z]{2,5}[\.]{0,1}/
if !re.test(url)
@msg = "Url not valid"
false
else
true
and then register it:
Sirius.BaseModel.register_validator("url_validator", UrlValidator)
In a model:
class Model extends Sirius.BaseModel
@attrs: ["url"]
@validate:
url:
url_validator : true