3 |
4 |
Usages & Examples
5 |
6 |
Built-in Rules
7 |
8 |
Here is an example form with different built-in rules:
9 |
10 |
11 | This example uses several built-in validation rules, such as
12 | required, regex, digit,
13 | length, integer and greaterThan,
14 | for the full list of built-in rules, check out the Validator / rules API.
15 |
16 |
17 | To reset the validation status, this example calls
ValidationBag.reset() method,
18 | for detail refer to
ValidationBag API.
19 |
20 |
21 |
Custom Rule
22 |
23 |
24 |
25 | Use Validator.custom() method for custom validation rule,
26 | this method accepts a callback function to perform custom validation logic,
27 | the callback function is expected to return an error message (or promise, see Async Validation) if validation fails.
28 | Optionally, you can provide the callback function's execution context object as the second parameter.
29 |
30 |
31 | In the above example, we are also using Validator.isEmpty() method,
32 | this method is internally used by Validator.required() method to determine if a field value is empty,
33 | since most validation rules apply only when the value is NOT empty, this method is also exposed as public API so that it can be used by custom code.
34 |
35 |
36 |
Cross Field Validation
37 |
Password validation
38 |
39 |
40 |
41 | In this example, the password field has ordinary validation rule that it's required and its minimum length is 6.
42 | The repeat field however, is much trickier.
43 | First of all, its value should match the password field, this means cross field validation.
44 | Secondary, when the form is not already submitted, it should not be validated if user haven't touched it,
45 | otherwise we will see validation error message for repeat field when user is just typing in password field but haven't touch the repeat field yet!
46 | Let's take a look at the code:
47 |
48 |
submit: function () {
49 | this.submitted = true;
50 | ...
51 | }
52 |
53 | We set the submitted field to true when user clicks the submit button.
54 |
55 |
'repeat, password': function (repeat, password) {
56 | if (this.submitted || this.validation.isTouched('repeat')) {
57 | return Validator.value(repeat).required().match(password);
58 | }
59 | }
60 |
61 | In the validators config, we use 'repeat, password' as key, so that the library would watch these 2 fields for us,
62 | note that now we expect the library to provide values of both repeat and password in the validator function.
63 | In the code, we only perform validation when the form is already submitted or the repeat field is already touched by user.
64 | We also enforce that the value of repeat field should match the value of password field.
65 |
66 |
67 | We use
ValidationBag.isTouch() method to detect if a field is touched by user,
68 | check out
ValidationBag API to find more details about this method and other similar utility methods.
69 |
70 |
71 |
Conditional validation
72 |
73 |
74 |
75 | This example demonstration the conditional validation use case,
76 | where the other field is only required when user selects the "Other fruit (please specify)" option.
77 | Like the previous example, we set a submitted field after user submitted,
78 | we watch both other and fruit field,
79 | and only perform validation when the form is submitted or other field is touched.
80 | There are also some differences. First, we use v-if="fruit === 'other'" to make the text field visible only when "Other fruit (please specify)" option is selected.
81 | Secondary, we skip the validation if the value of fruit !== 'other'.
82 |
83 |
84 | Note that the library would use the first property name as error field name, which is 'other',
85 | thus we use use it as opposed to 'fruit' when checking for error to display: validation.hasError('other').
86 |
87 |
88 |
Async Validation
89 |
Basic
90 |
91 |
92 |
93 | Async validation is also supported by the Validator.custom() method,
94 | comparing to Custom Rule, the difference is that instead of returning the error message directly,
95 | the callback function now returns a promise, the promise should resolve to error message if validation fails.
96 |
97 |
return Validator.custom(function () {
98 | if (!Validator.isEmpty(value)) {
99 | return Promise.delay(1000)
100 | .then(function() {
101 | if (value !== 'vuejs.org') {
102 | return 'Already taken!';
103 | }
104 | });
105 | }
106 | });
107 |
108 | Here we simply delay the execution for 1 second, in the real world, you probably will make an ajax request to server.
109 |
110 |
111 | In this example, we are using
Blue Bird for promise,
112 | but you can use which ever promise library you prefer.
113 |
114 |
<i v-if="validation.isValidating('domain')" class="fa fa-spin fa-spinner"></i>
115 | <i v-if="domain && validation.isPassed('domain')" class="text-success fa fa-check-circle"></i>
116 |
117 | In the template HTML, we use ValidationBag.isValidating() to show an animating spinner when async validation is in progress,
118 | we also use ValidationBag.isPassed() to show a green tick when validation successes.
119 |
120 |
121 |
Dedouncing & caching
122 |
123 |
124 | You might notice 2 problems in previous example:
125 |
126 |
127 | - The async validation is invoked again when you clicks submit, this is not necessary.
128 | - The async validation is activated every time user hits the keyboard, this would cause performance issue if we are making ajax request.
129 |
130 |
131 |
132 | To tackle the first problem, we use the cache option and set it to true,
133 | to tell the library we would like to cache all previous results.
134 | For the second problem, we set the debounce option to half a second,
135 | so that the async validation is postponed until user stops typing for half a second.
136 | Lastly, the validator function is now specified via the validator option.
137 |
138 |
139 | The cache option can also take a 'all' string, which is equivalent to true,
140 | also the 'last' string would tell to framework to only cache the last result,
141 | this is useful when you only want to enable caching for form submission.
142 |
143 |
144 |
Custom Component
145 |
146 |
147 |
148 | The library can work with any custom component as long as the component supports v-model.
149 | The above example demonstrates using a custom CheckboxGroup component that wraps the iCheck library.
150 |
151 |
152 |
Dynamic Form
153 |
154 |
155 |
156 | To implement dynamic form (form created at runtime), move the form related HTML and codes into a separated child component and expose a validate method,
157 | this would result in multiple ValidationBag instances attached to the child components.
158 | You can then invoke the validate method from parent to trigger validation logic.
159 |
160 |
161 |
Custom Error Message / Localization
162 |
163 |
164 | Starting from 0.13.0, the error message templates is updated to use the same message key as rule name,
165 | if you were using version lower than 0.13.0 and have defined your customized templates,
166 | you will have to update your templates according to the changes
here.
167 |
168 |
169 |
Overriding Global Error Message
170 |
171 |
172 |
173 | Use SimpleVueValidator.extendTemplates() method (or Vue.use(SimpleVueValidator, {templates: {...})) to override the default error messages.
174 | This can also be used to provide localized messages to the library.
175 |
176 |
177 | See
templates.js for all the text templates you can replace.
178 |
179 |
180 |
Component Based Error Message
181 |
182 |
183 |
184 | Use Validator.create({templates: ...}) to create a new Validator with customized error messages.
185 | Overriding the error messages template this way will have the scope limit to the newly created Validator, so it won't affect
186 | the global settings.
187 |
188 |
189 |
Field Based Error Message
190 |
191 |
192 |
193 | For all the built-in rules, you can pass a custom message as the last argument to specify the error message for the current field only.
194 |
195 |
196 |
197 |