1 | validatorjs
|
2 | ===========
|
3 |
|
4 | [![Build Status](https://travis-ci.org/skaterdav85/validatorjs.png?branch=master)](https://travis-ci.org/skaterdav85/validatorjs)
|
5 |
|
6 | The validatorjs library makes data validation in JavaScript very easy in both the browser and Node.js. This library was inspired by the [Laravel framework's Validator](http://laravel.com/docs/validation).
|
7 |
|
8 | ## Why use validatorjs?
|
9 |
|
10 | * Not dependent on any libraries.
|
11 | * Works in both the browser and Node.
|
12 | * Readable and declarative validation rules.
|
13 | * Error messages with multilingual support.
|
14 | * AMD/Require.js and CommonJS/Browserify support.
|
15 |
|
16 | ## Installation
|
17 |
|
18 | Grab validatorjs from Bower, NPM, or the /dist directory on Github:
|
19 |
|
20 | ```
|
21 | bower install validatorjs
|
22 | ```
|
23 |
|
24 | ```
|
25 | npm install validatorjs
|
26 | ```
|
27 |
|
28 | ### Browser
|
29 |
|
30 | ```html
|
31 | <script src="validator.min.js"></script>
|
32 | ```
|
33 |
|
34 | ### Node.js / Browserify
|
35 |
|
36 | ```js
|
37 | var Validator = require('validatorjs');
|
38 | ```
|
39 |
|
40 | ### Basic Usage
|
41 |
|
42 | ```js
|
43 | var validation = new Validator(data, rules [, customErrorMessages]);
|
44 | ```
|
45 |
|
46 | __data__ {Object} - The data you want to validate
|
47 |
|
48 | __rules__ {Object} - Validation rules
|
49 |
|
50 | __customErrorMessages__ {Object} - Optional custom error messages to return
|
51 |
|
52 | #### Example 1 - Passing validation
|
53 |
|
54 | ```js
|
55 | var data = {
|
56 | name: 'John',
|
57 | email: 'johndoe@gmail.com',
|
58 | age: 28
|
59 | };
|
60 |
|
61 | var rules = {
|
62 | name: 'required',
|
63 | email: 'required|email',
|
64 | age: 'min:18'
|
65 | };
|
66 |
|
67 | var validation = new Validator(data, rules);
|
68 |
|
69 | validation.passes(); // true
|
70 | validation.fails(); // false
|
71 | ```
|
72 |
|
73 | To apply validation rules to the _data_ object, use the same object key names for the _rules_ object.
|
74 |
|
75 | #### Example 2 - Failing validation
|
76 |
|
77 | ```js
|
78 | var validation = new Validator({
|
79 | name: 'D',
|
80 | email: 'not an email address.com'
|
81 | }, {
|
82 | name: 'size:3',
|
83 | email: 'required|email'
|
84 | });
|
85 |
|
86 | validation.fails(); // true
|
87 | validation.passes(); // false
|
88 |
|
89 | // Error messages
|
90 | validation.errors.first('email'); // 'The email format is invalid.'
|
91 | validation.errors.get('email'); // returns an array of all email error messages
|
92 | ```
|
93 |
|
94 | ### Nested rules
|
95 |
|
96 | Nested objects can also be validated. There are two ways to declare validation rules for nested objects. The first way is to declare the validation rules with a corresponding nested object structure that reflects the data. The second way is to declare validation rules with flattened key names. For example, to validate the following data:
|
97 |
|
98 | ```js
|
99 | var data = {
|
100 | name: 'John',
|
101 | bio: {
|
102 | age: 28,
|
103 | education: {
|
104 | primary: 'Elementary School',
|
105 | secondary: 'Secondary School'
|
106 | }
|
107 | }
|
108 | };
|
109 | ```
|
110 |
|
111 | We could declare our validation rules as follows:
|
112 |
|
113 | ```js
|
114 | var nested = {
|
115 | name: 'required',
|
116 | bio: {
|
117 | age: 'min:18',
|
118 | education: {
|
119 | primary: 'string',
|
120 | secondary: 'string'
|
121 | }
|
122 | }
|
123 | };
|
124 |
|
125 | // OR
|
126 |
|
127 | var flattened = {
|
128 | 'name': 'required',
|
129 | 'bio.age': 'min:18'
|
130 | 'bio.education.primary': 'string',
|
131 | 'bio.education.secondary': 'string'
|
132 | };
|
133 | ```
|
134 |
|
135 | ### Available Rules
|
136 |
|
137 | Validation rules do not have an implicit 'required'. If a field is _undefined_ or an empty string, it will pass validation. If you want a validation to fail for undefined or '', use the _required_ rule.
|
138 |
|
139 | #### accepted
|
140 |
|
141 | The field under validation must be yes, on, 1 or true. This is useful for validating "Terms of Service" acceptance.
|
142 |
|
143 | #### after:date
|
144 |
|
145 | The field under validation must be after the given date.
|
146 |
|
147 | #### after_or_equal:date
|
148 |
|
149 | The field unter validation must be after or equal to the given field
|
150 |
|
151 | #### alpha
|
152 |
|
153 | The field under validation must be entirely alphabetic characters.
|
154 |
|
155 | #### alpha_dash
|
156 |
|
157 | The field under validation may have alpha-numeric characters, as well as dashes and underscores.
|
158 |
|
159 | #### alpha_num
|
160 |
|
161 | The field under validation must be entirely alpha-numeric characters.
|
162 |
|
163 | #### array
|
164 |
|
165 | The field under validation must be an array.
|
166 |
|
167 | #### before:date
|
168 |
|
169 | The field under validation must be before the given date.
|
170 |
|
171 |
|
172 | #### before_or_equal:date
|
173 |
|
174 | The field under validation must be before or equal to the given date.
|
175 |
|
176 | #### between:min,max
|
177 |
|
178 | The field under validation must have a size between the given min and max. Strings, numerics, and files are evaluated in the same fashion as the size rule.
|
179 |
|
180 | #### boolean
|
181 |
|
182 | The field under validation must be a boolean value of the form `true`, `false`, `0`, `1`, `'true'`, `'false'`, `'0'`, `'1'`,
|
183 |
|
184 | #### confirmed
|
185 |
|
186 | The field under validation must have a matching field of foo_confirmation. For example, if the field under validation is password, a matching password_confirmation field must be present in the input.
|
187 |
|
188 | #### date
|
189 |
|
190 | The field under validation must be a valid date format which is acceptable by Javascript's `Date` object.
|
191 |
|
192 | #### digits:value
|
193 |
|
194 | The field under validation must be numeric and must have an exact length of value.
|
195 |
|
196 | #### different:attribute
|
197 |
|
198 | The given field must be different than the field under validation.
|
199 |
|
200 | #### email
|
201 |
|
202 | The field under validation must be formatted as an e-mail address.
|
203 |
|
204 | #### in:foo,bar,...
|
205 |
|
206 | The field under validation must be included in the given list of values. The field can be an array or string.
|
207 |
|
208 | #### integer
|
209 |
|
210 | The field under validation must have an integer value.
|
211 |
|
212 | #### max:value
|
213 |
|
214 | Validate that an attribute is no greater than a given size
|
215 |
|
216 | _Note: Maximum checks are inclusive._
|
217 |
|
218 | #### min:value
|
219 |
|
220 | Validate that an attribute is at least a given size.
|
221 |
|
222 | _Note: Minimum checks are inclusive._
|
223 |
|
224 | #### not_in:foo,bar,...
|
225 |
|
226 | The field under validation must not be included in the given list of values.
|
227 |
|
228 | #### numeric
|
229 |
|
230 | Validate that an attribute is numeric. The string representation of a number will pass.
|
231 |
|
232 | #### required
|
233 |
|
234 | Checks if the length of the String representation of the value is >
|
235 |
|
236 | #### required_if:anotherfield,value
|
237 |
|
238 | The field under validation must be present and not empty if the anotherfield field is equal to any value.
|
239 |
|
240 | #### required_unless:anotherfield,value
|
241 |
|
242 | The field under validation must be present and not empty unless the anotherfield field is equal to any value.
|
243 |
|
244 | #### required_with:foo,bar,...
|
245 |
|
246 | The field under validation must be present and not empty only if any of the other specified fields are present.
|
247 |
|
248 | #### required_with_all:foo,bar,...
|
249 |
|
250 | The field under validation must be present and not empty only if all of the other specified fields are present.
|
251 |
|
252 | #### required_without:foo,bar,...
|
253 |
|
254 | The field under validation must be present and not empty only when any of the other specified fields are not present.
|
255 |
|
256 | #### required_without_all:foo,bar,...
|
257 |
|
258 | The field under validation must be present and not empty only when all of the other specified fields are not present.
|
259 |
|
260 | #### same:attribute
|
261 |
|
262 | The given field must match the field under validation.
|
263 |
|
264 | #### size:value
|
265 |
|
266 | The field under validation must have a size matching the given value. For string data, value corresponds to the number of characters. For numeric data, value corresponds to a given integer value.
|
267 |
|
268 | #### string
|
269 |
|
270 | The field under validation must be a string.
|
271 |
|
272 | #### url
|
273 |
|
274 | Validate that an attribute has a valid URL format
|
275 |
|
276 | #### regex:pattern
|
277 |
|
278 | The field under validation must match the given regular expression.
|
279 |
|
280 | **Note**: When using the ``regex`` pattern, it may be necessary to specify rules in an array instead of using pipe delimiters, especially if the regular expression contains a pipe character.
|
281 | For each backward slash that you used in your regex pattern, you must escape each one with another backward slash.
|
282 |
|
283 | #### Example 3 - Regex validation
|
284 |
|
285 | ```js
|
286 | var validation = new Validator({
|
287 | name: 'Doe',
|
288 | salary: '10,000.00',
|
289 | yearOfBirth: '1980'
|
290 | }, {
|
291 | name: 'required|size:3',
|
292 | salary: ['required', 'regex:/^(?!0\\.00)\\d{1,3}(,\\d{3})*(\\.\\d\\d)?$/'],
|
293 | yearOfBirth: ['required', 'regex:/^(19|20)[\\d]{2,2}$/']
|
294 | });
|
295 |
|
296 | validation.fails(); // false
|
297 | validation.passes(); // true
|
298 |
|
299 | ```
|
300 |
|
301 | ### Registering Custom Validation Rules
|
302 |
|
303 | ```js
|
304 | Validator.register(name, callbackFn, errorMessage);
|
305 | ```
|
306 |
|
307 | __name__ {String} - The name of the rule.
|
308 |
|
309 | __callbackFn__ {Function} - Returns a boolean to represent a successful or failed validation.
|
310 |
|
311 | __errorMessage__ {String} - An optional string where you can specify a custom error message. _:attribute_ inside errorMessage will be replaced with the attribute name.
|
312 |
|
313 | ```js
|
314 | Validator.register('telephone', function(value, requirement, attribute) { // requirement parameter defaults to null
|
315 | return value.match(/^\d{3}-\d{3}-\d{4}$/);
|
316 | }, 'The :attribute phone number is not in the format XXX-XXX-XXXX.');
|
317 | ```
|
318 |
|
319 | ### Asynchronous validation
|
320 |
|
321 | Register an asynchronous rule which accepts a `passes` callback:
|
322 |
|
323 | ```js
|
324 | Validator.registerAsync('username_available', function(username, attribute, req, passes) {
|
325 | // do your database/api checks here etc
|
326 | // then call the `passes` method where appropriate:
|
327 | passes(); // if username is available
|
328 | passes(false, 'Username has already been taken.'); // if username is not available
|
329 | });
|
330 | ```
|
331 |
|
332 | Then call your validator passing a callback to `fails` or `passes` like so:
|
333 |
|
334 | ```js
|
335 | var validator = new Validator({ username: 'test123' }, { username: 'required|min:3|username_available' });
|
336 | validator.passes(function() {
|
337 | // Validation passed
|
338 | });
|
339 |
|
340 | // Or call fails()
|
341 | validator.fails(function() {
|
342 | // Error message:
|
343 | validator.errors.first('username');
|
344 | });
|
345 | ```
|
346 |
|
347 | Note: if you attempt to call `passes` or `fails` without a callback and the validator detects there are asynchronous validation rules, an exception will be thrown.
|
348 |
|
349 | ### Error Messages
|
350 |
|
351 | This contructor will automatically generate error messages for validation rules that failed.
|
352 |
|
353 | If there are errors, the Validator instance will have its __errors__ property object populated with the error messages for all failing attributes. The methods and properties on the __errors__ property object are:
|
354 |
|
355 | #### .first(attribute)
|
356 |
|
357 | returns the first error message for an attribute, false otherwise
|
358 |
|
359 | #### .get(attribute)
|
360 |
|
361 | returns an array of error messages for an attribute, or an empty array if there are no errors
|
362 |
|
363 | #### .all()
|
364 |
|
365 | returns an object containing all error messages for all failing attributes
|
366 |
|
367 | #### .has(attribute)
|
368 |
|
369 | returns true if error messages exist for an attribute, false otherwise
|
370 |
|
371 | #### .errorCount
|
372 |
|
373 | the number of validation errors
|
374 |
|
375 | ```js
|
376 | var validation = new Validator(input, rules);
|
377 | validation.errors.first('email'); // returns first error message for email attribute
|
378 | validator.errors.get('email'); // returns an array of error messages for the email attribute
|
379 | ```
|
380 |
|
381 | ### Custom Error Messages
|
382 |
|
383 | If you need a specific error message and you don't want to override the default one, you can pass an override as the third argument to the Validator object, just like with [Laravel](http://laravel.com/docs/validation#custom-error-messages).
|
384 |
|
385 | ```js
|
386 | var input = {
|
387 | name: ''
|
388 | };
|
389 |
|
390 | var rules = {
|
391 | name : 'required'
|
392 | };
|
393 |
|
394 | var validation = new Validator(input, rules, { required: 'You forgot to give a :attribute' });
|
395 | validation.errors.first('name'); // returns 'You forgot to give a name'
|
396 | ```
|
397 |
|
398 | Some of the validators have string and numeric versions. You can change them too.
|
399 |
|
400 | ```js
|
401 | var input = {
|
402 | username: 'myusernameistoolong'
|
403 | };
|
404 |
|
405 | var rules = {
|
406 | username : 'max:16'
|
407 | };
|
408 |
|
409 | var validation = new Validator(input, rules, {
|
410 | max: {
|
411 | string: 'The :attribute is too long. Max length is :max.'
|
412 | }
|
413 | });
|
414 |
|
415 | validation.errors.first('username'); // returns 'The username is too long. Max length is 16.'
|
416 | ```
|
417 |
|
418 | You can even provide error messages on a per attribute basis! Just set the message's key to 'validator.attribute'
|
419 |
|
420 | ```js
|
421 | var input = { name: '', email: '' };
|
422 | var rules = { name : 'required', email : 'required' };
|
423 |
|
424 | var validation = new Validator(input, rules, {
|
425 | "required.email": "Without an :attribute we can't reach you!"
|
426 | });
|
427 |
|
428 | validation.errors.first('name'); // returns 'The name field is required.'
|
429 | validation.errors.first('email'); // returns 'Without an email we can\'t reach you!'
|
430 | ```
|
431 |
|
432 | ### Custom attribute names
|
433 |
|
434 | To display a custom "friendly" attribute name in error messages, use `.setAttributeNames()`
|
435 |
|
436 | ```js
|
437 | var validator = new Validator({ name: '' }, { name: 'required' });
|
438 | validator.setAttributeNames({ name: 'custom_name' });
|
439 | if (validator.fails()) {
|
440 | validator.errors.first('name'); // "The custom_name field is required."
|
441 | }
|
442 | ```
|
443 |
|
444 | Alternatively you can supply global custom attribute names in your lang with the `attributes` property.
|
445 |
|
446 | You can also configure a custom attribute formatter:
|
447 |
|
448 | ```js
|
449 | // Configure global formatter.
|
450 | Validator.setAttributeFormatter(function(attribute) {
|
451 | return attribute.replace(/_/g, ' ');
|
452 | });
|
453 |
|
454 | // Or configure formatter for particular instance.
|
455 | var validator = new Validator({ first_name: '' }, { first_name: 'required' });
|
456 | validator.setAttributeFormatter(function(attribute) {
|
457 | return attribute.replace(/_/g, ' ');
|
458 | });
|
459 | if (validator.fails()) {
|
460 | console.log(validator.errors.first('first_name')); // The first name field is required.
|
461 | }
|
462 | ```
|
463 |
|
464 | Note: by default all _[] characters will be replaced with spaces.
|
465 |
|
466 | ### Language Support
|
467 |
|
468 | Error messages are in English by default. To include another language in the browser, reference the language file in a script tag and call `Validator.useLang('lang_code')`.
|
469 |
|
470 | ```html
|
471 | <script src="dist/validator.min.js"></script>
|
472 | <script src="dist/lang/ru.js"></script>
|
473 | <script>
|
474 | Validator.useLang('es');
|
475 | </script>
|
476 | ```
|
477 |
|
478 | In Node, it will automatically pickup on the language source files.
|
479 |
|
480 | ```js
|
481 | var Validator = require('validatorjs');
|
482 | Validator.useLang('ru');
|
483 | ```
|
484 |
|
485 | If you don't see support for your language, please add one to `src/lang`!
|
486 |
|
487 | You can also add your own custom language by calling `setMessages`:
|
488 |
|
489 | ```js
|
490 | Validator.setMessages('lang_code', {
|
491 | required: 'The :attribute field is required.',
|
492 | ....
|
493 | ....
|
494 | });
|
495 | ```
|
496 |
|
497 | Get the raw object of messages for the given language:
|
498 |
|
499 | ```js
|
500 | Validator.getMessages('lang_code');
|
501 | ```
|
502 |
|
503 | Switch the default language used by the validator:
|
504 |
|
505 | ```js
|
506 | Validator.useLang('lang_code');
|
507 | ```
|
508 |
|
509 | Get the default language being used:
|
510 |
|
511 | ```js
|
512 | Validator.getDefaultLang(); // returns e.g. 'en'
|
513 | ```
|
514 |
|
515 | Override default messages for language:
|
516 |
|
517 | ```js
|
518 | var messages = Validator.getMessages('en');
|
519 | messages.required = 'Whoops, :attribute field is required.';
|
520 | Validator.setMessages('en', messages);
|
521 | ```
|