Syntax of addRule
For the syntax I mean what are the rules which governed the .addRule()
. Knowing the syntax can be useful to you to be really effective.
The syntax
The syntax is really simple:
addRule("a field -> a rule")
addRule("user_email -> email")
Multiple parameters
A rule can have multiple parameters like range
, higher
, less
, min_length
, max_length
... You need to see the documentation of a rule to see if it has parameters or not.
addRule("a field -> range: 3, 10")
addRule("age -> range: 18, 100")
One field or more
Because sometimes we have multiple fields that follow the same rules i decided to improve the behavior of the parser. You can specify one or more field like that :
addRule("website -> url")
addRule("website, twitter, linkedin -> optional: ([twitter, linkedin]) | url")
Multiple rules
As you could see we can separate the rules by |
in order to execute multiple rule on same field.
addRule("file -> url | min_length: 4 | start_with: file://")
Escapement
To use some characters like |,:
in parameter's rule you need to escape the parameter by surrounding him.
To use parentheses just escape them with \)
. The (
don't need escaping.
.addRule("website, twitter, linkedin -> optional: ([twitter, linkedin]) | url")
Replacements
Because sometimes we have dynamic value i have create a replacement way with :NUMBER
.
addRule("new_email -> diff: (:1) | email", oldEmail)
This code check if new_email
field is different that diff: (:1)
where :1
will be replace by oldEmail
the number match with the n-param number here params[0]
(+1) is oldEmail.
Sometime we need to escape charater like () like in regex for example. You need to use $NUMBER
(same as :NUMBER
).
That's mean that the replacer will be replaced at the end, after the parsing of the rule.
How to know if the syntax is correct ?
If the syntax is not correct (you need to not ignore the RuleParseException) you will see in your terminal an error message like that:
kwizzy.validation.exceptions.RuleLexerException
at kwizzy.validation.parser.RuleLexer.lex(RuleLexer.java:136)
at util.UtilTest.testErrorLexer(UtilTest.java:58)
at rules.RuleLexerTest.testRuleLEexerNotOk(RuleLexerTest.java:36)
...
confirm (123
^
Lexer: Unexpected symbol: (. (Index: 8)
kwizzy.validation.exceptions.RuleLexerException
at kwizzy.validation.parser.RuleLexer.lex(RuleLexer.java:94)
at util.UtilTest.testErrorLexer(UtilTest.java:58)
...
wertyuio
^
No rule matching for rule name: wertyuio. (Index: 0)
Other errors exists obviously. It was something that took a lot of effort to get this result.