UNPKG

13.9 kBMarkdownView Raw
1validatorjs
2===========
3
4[![Build Status](https://travis-ci.org/skaterdav85/validatorjs.png?branch=master)](https://travis-ci.org/skaterdav85/validatorjs)
5
6The 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
18Grab validatorjs from Bower, NPM, or the /dist directory on Github:
19
20```
21bower install validatorjs
22```
23
24```
25npm 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
37var Validator = require('validatorjs');
38```
39
40### Basic Usage
41
42```js
43var 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
55var data = {
56 name: 'John',
57 email: 'johndoe@gmail.com',
58 age: 28
59};
60
61var rules = {
62 name: 'required',
63 email: 'required|email',
64 age: 'min:18'
65};
66
67var validation = new Validator(data, rules);
68
69validation.passes(); // true
70validation.fails(); // false
71```
72
73To 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
78var validation = new Validator({
79 name: 'D',
80 email: 'not an email address.com'
81}, {
82 name: 'size:3',
83 email: 'required|email'
84});
85
86validation.fails(); // true
87validation.passes(); // false
88
89// Error messages
90validation.errors.first('email'); // 'The email format is invalid.'
91validation.errors.get('email'); // returns an array of all email error messages
92```
93
94### Nested rules
95
96Nested 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
99var data = {
100 name: 'John',
101 bio: {
102 age: 28,
103 education: {
104 primary: 'Elementary School',
105 secondary: 'Secondary School'
106 }
107 }
108};
109```
110
111We could declare our validation rules as follows:
112
113```js
114var 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
127var 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
137Validation 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
141The field under validation must be yes, on, 1 or true. This is useful for validating "Terms of Service" acceptance.
142
143#### after:date
144
145The field under validation must be after the given date.
146
147#### after_or_equal:date
148
149The field unter validation must be after or equal to the given field
150
151#### alpha
152
153The field under validation must be entirely alphabetic characters.
154
155#### alpha_dash
156
157The field under validation may have alpha-numeric characters, as well as dashes and underscores.
158
159#### alpha_num
160
161The field under validation must be entirely alpha-numeric characters.
162
163#### array
164
165The field under validation must be an array.
166
167#### before:date
168
169The field under validation must be before the given date.
170
171
172#### before_or_equal:date
173
174The field under validation must be before or equal to the given date.
175
176#### between:min,max
177
178The 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
182The field under validation must be a boolean value of the form `true`, `false`, `0`, `1`, `'true'`, `'false'`, `'0'`, `'1'`,
183
184#### confirmed
185
186The 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
190The field under validation must be a valid date format which is acceptable by Javascript's `Date` object.
191
192#### digits:value
193
194The field under validation must be numeric and must have an exact length of value.
195
196#### different:attribute
197
198The given field must be different than the field under validation.
199
200#### email
201
202The field under validation must be formatted as an e-mail address.
203
204#### in:foo,bar,...
205
206The field under validation must be included in the given list of values. The field can be an array or string.
207
208#### integer
209
210The field under validation must have an integer value.
211
212#### max:value
213
214Validate that an attribute is no greater than a given size
215
216_Note: Maximum checks are inclusive._
217
218#### min:value
219
220Validate that an attribute is at least a given size.
221
222_Note: Minimum checks are inclusive._
223
224#### not_in:foo,bar,...
225
226The field under validation must not be included in the given list of values.
227
228#### numeric
229
230Validate that an attribute is numeric. The string representation of a number will pass.
231
232#### required
233
234Checks if the length of the String representation of the value is >
235
236#### required_if:anotherfield,value
237
238The 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
242The 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
246The 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
250The 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
254The 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
258The 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
262The given field must match the field under validation.
263
264#### size:value
265
266The 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
270The field under validation must be a string.
271
272#### url
273
274Validate that an attribute has a valid URL format
275
276#### regex:pattern
277
278The 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.
281For 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
286var 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
296validation.fails(); // false
297validation.passes(); // true
298
299```
300
301### Registering Custom Validation Rules
302
303```js
304Validator.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
314Validator.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
321Register an asynchronous rule which accepts a `passes` callback:
322
323```js
324Validator.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
332Then call your validator passing a callback to `fails` or `passes` like so:
333
334```js
335var validator = new Validator({ username: 'test123' }, { username: 'required|min:3|username_available' });
336validator.passes(function() {
337 // Validation passed
338});
339
340// Or call fails()
341validator.fails(function() {
342 // Error message:
343 validator.errors.first('username');
344});
345```
346
347Note: 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
351This contructor will automatically generate error messages for validation rules that failed.
352
353If 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
357returns the first error message for an attribute, false otherwise
358
359#### .get(attribute)
360
361returns an array of error messages for an attribute, or an empty array if there are no errors
362
363#### .all()
364
365returns an object containing all error messages for all failing attributes
366
367#### .has(attribute)
368
369returns true if error messages exist for an attribute, false otherwise
370
371#### .errorCount
372
373the number of validation errors
374
375```js
376var validation = new Validator(input, rules);
377validation.errors.first('email'); // returns first error message for email attribute
378validator.errors.get('email'); // returns an array of error messages for the email attribute
379```
380
381### Custom Error Messages
382
383If 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
386var input = {
387 name: ''
388};
389
390var rules = {
391 name : 'required'
392};
393
394var validation = new Validator(input, rules, { required: 'You forgot to give a :attribute' });
395validation.errors.first('name'); // returns 'You forgot to give a name'
396```
397
398Some of the validators have string and numeric versions. You can change them too.
399
400```js
401var input = {
402 username: 'myusernameistoolong'
403};
404
405var rules = {
406 username : 'max:16'
407};
408
409var validation = new Validator(input, rules, {
410 max: {
411 string: 'The :attribute is too long. Max length is :max.'
412 }
413});
414
415validation.errors.first('username'); // returns 'The username is too long. Max length is 16.'
416```
417
418You can even provide error messages on a per attribute basis! Just set the message's key to 'validator.attribute'
419
420```js
421var input = { name: '', email: '' };
422var rules = { name : 'required', email : 'required' };
423
424var validation = new Validator(input, rules, {
425 "required.email": "Without an :attribute we can't reach you!"
426});
427
428validation.errors.first('name'); // returns 'The name field is required.'
429validation.errors.first('email'); // returns 'Without an email we can\'t reach you!'
430```
431
432### Custom attribute names
433
434To display a custom "friendly" attribute name in error messages, use `.setAttributeNames()`
435
436```js
437var validator = new Validator({ name: '' }, { name: 'required' });
438validator.setAttributeNames({ name: 'custom_name' });
439if (validator.fails()) {
440 validator.errors.first('name'); // "The custom_name field is required."
441}
442```
443
444Alternatively you can supply global custom attribute names in your lang with the `attributes` property.
445
446You can also configure a custom attribute formatter:
447
448```js
449// Configure global formatter.
450Validator.setAttributeFormatter(function(attribute) {
451 return attribute.replace(/_/g, ' ');
452});
453
454// Or configure formatter for particular instance.
455var validator = new Validator({ first_name: '' }, { first_name: 'required' });
456validator.setAttributeFormatter(function(attribute) {
457 return attribute.replace(/_/g, ' ');
458});
459if (validator.fails()) {
460 console.log(validator.errors.first('first_name')); // The first name field is required.
461}
462```
463
464Note: by default all _[] characters will be replaced with spaces.
465
466### Language Support
467
468Error 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
478In Node, it will automatically pickup on the language source files.
479
480```js
481var Validator = require('validatorjs');
482Validator.useLang('ru');
483```
484
485If you don't see support for your language, please add one to `src/lang`!
486
487You can also add your own custom language by calling `setMessages`:
488
489```js
490Validator.setMessages('lang_code', {
491 required: 'The :attribute field is required.',
492 ....
493 ....
494});
495```
496
497Get the raw object of messages for the given language:
498
499```js
500Validator.getMessages('lang_code');
501```
502
503Switch the default language used by the validator:
504
505```js
506Validator.useLang('lang_code');
507```
508
509Get the default language being used:
510
511```js
512Validator.getDefaultLang(); // returns e.g. 'en'
513```
514
515Override default messages for language:
516
517```js
518var messages = Validator.getMessages('en');
519messages.required = 'Whoops, :attribute field is required.';
520Validator.setMessages('en', messages);
521```