forked from ansman/validate.js
/
index.html
1552 lines (1434 loc) · 58.8 KB
/
index.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Validate.js</title>
<link rel="shortcut icon" type="image/png" href="favicon.png">
<meta name="viewport" content="width=device-width, user-scalable=0">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.0.2/css/bootstrap.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/7.4/styles/default.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/7.4/styles/github.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/7.4/highlight.min.js"></script>
<script>hljs.initHighlightingOnLoad();</script>
<script src="https://cdn.jsdelivr.net/xdate/0.8/xdate.min.js"></script>
<script src="validate.js"></script>
<style>
html, body {
min-height: 100%;
height: 100%;
}
body {
font-weight: 200;
font-family: Helvetica, Arial, sans-serif;
}
h1, h2, h3 {
font-weight: 200;
}
#fork-me {
position: absolute;
right: 0;
top: 0;
-webkit-transform: translateZ(0);
}
#sidebar {
background-color: #F7F5FA;
box-sizing: border-box;
padding-top: 10px;
padding-left: 10px;
overflow-y: scroll;
width: 299px;
border-right: 1px solid #eee;
position: fixed;
left: 0;
top: 0;
height: 100%;
min-height: 100%;
max-height: 100%;
}
#sidebar a {
color: #333;
text-shadow: 0 1px 0 #FFF;
}
#sidebar ul {
list-style: none;
margin: 0;
padding-left: 10px;
}
#sidebar > ul > li {
margin-bottom: 10px;
}
#sidebar > ul > li > a {
font-size: 16px;
font-weight: 400;
}
#sidebar ul ul li {
padding-left: 10px;
position: relative;
}
#sidebar ul ul li:after {
display: block;
content: '-';
position: absolute;
left: 0px;
top: 0;
}
#sidebar ul ul li.external:after {
content: "»";
}
#content {
margin-left: 299px;
-webkit-transform: translateZ(0);
}
#scroller {
position: relative;
}
#scroll-content {
max-width: 800px;
min-width: 640px;
padding: 0 30px 30px;
}
#scroll-content > div {
padding: 10px 0;
}
#scroll-content > div:first-child {
padding-top: 0;
}
#validate-js h2 {
margin-top: 20px;
}
h1 {
font-size: 50px;
text-transform: uppercase;
border-bottom: 5px solid #333;
display: inline-block;
}
.download {
margin-top: 20px;
}
.download .btn {
width: 250px;
display: inline-block;
vertical-align: top;
}
.download .info {
display: inline-block;
font-size: 12px;
margin-left: 5px;
}
.download .badges a:hover {
text-decoration: none;
}
.dependencies {
margin-top: 20px;
}
h2 {
margin-top: 0;
}
.signature {
margin-bottom: 10px;
}
.signature b {
margin-right: 5px;
font-size: 18px;
}
pre > code {
padding: 0;
background-color: transparent;
}
.notes {
font-style: italic;
}
ul > li > code {
display: inline-block;
margin-bottom: 3px;
}
#validators > div {
padding: 10px 0px;
}
#changelog h3 {
font-size: 14px;
}
#changelog h3 .version {
font-size: 18px;
}
@media (max-width: 768px) {
body {
padding-left: 0;
}
#fork-me {
display: none;
}
.header {
text-align: center;
}
.download {
text-align: center;
}
.download .btn {
width: 100%;
margin-bottom: 3px;
}
h1 {
font-size: 40px;
margin-top: 0;
}
#sidebar {
display: none;
}
#content {
margin-left: 0;
}
#scroll-content {
min-width: 0;
padding: 10px;
}
code {
white-space: normal;
}
pre {
overflow: scroll;
}
pre code {
min-width: 600px;
}
}
</style>
<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','https://www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-45797376-1', 'validatejs.org');
ga('require', 'displayfeatures');
ga('send', 'pageview');
</script>
</head>
<body>
<nav id="sidebar">
<ul>
<li>
<a href="#validate-js">Validate.js</a>
<ul>
<li class="external">
<a href="https://github.com/ansman/validate.js">GitHub Repository</a>
</li>
<li class="external">
<a href="docs/validate.html">Annotated source</a>
</li>
</ul>
</li>
<li>
<a href="#overview">Overview</a>
<ul>
<li><a href="#supported-runtimes">Supported runtimes</a></li>
<li><a href="#acknowledgements">Acknowledgements</a></li>
</ul>
</li>
<li><a href="#constraints">Constraints</a></li>
<li>
<a href="#validate">Validate function</a>
<ul>
<li><a href="#validate-async">Async validation</a></li>
<li><a href="#validate-nested">Nested validation</a></li>
<li><a href="#validate-default-options">Default options</a></li>
</ul>
</li>
<li>
<a href="#custom-validator">Writing your own validator</a>
<ul>
<li><a href="#custom-validator-async">Writing an async validator</a></li>
</ul>
</li>
<li>
<a href="#validators">Validators</a>
<ul>
<li><a href="#validators-presence">Presence</a></li>
<li><a href="#validators-length">Length</a></li>
<li><a href="#validators-numericality">Numericality</a></li>
<li><a href="#validators-datetime">Datetime</a></li>
<li><a href="#validators-date">Date</a></li>
<li><a href="#validators-format">Format</a></li>
<li><a href="#validators-inclusion">Inclusion</a></li>
<li><a href="#validators-exclusion">Exclusion</a></li>
<li><a href="#validators-email">Email</a></li>
</ul>
</li>
<li>
<a href="#installing">Installing</a>
<ul>
<li><a href="#installing-node">node.js</a></li>
<li><a href="#installing-browser">Browser</a></li>
<li><a href="#installing-bower">Bower</a></li>
</ul>
</li>
<li>
<a href="#changelog">Changelog</a>
<ul>
<li><a href="#changelog-0-4-0">0.4.0</a></li>
<li><a href="#changelog-0-3-2">0.3.2</a></li>
<li><a href="#changelog-0-3-1">0.3.1</a></li>
<li><a href="#changelog-0-3-0">0.3.0</a></li>
<li><a href="#changelog-0-2-0">0.2.0</a></li>
<li><a href="#changelog-0-1-3">0.1.3</a></li>
<li><a href="#changelog-0-1-2">0.1.2</a></li>
<li><a href="#changelog-0-1-1">0.1.1</a></li>
<li><a href="#changelog-0-1-0">0.1.0</a></li>
</ul>
</li>
</ul>
</nav>
<div id="content">
<div id="scroller">
<a id="fork-me" href="https://github.com/ansman/validate.js"><img src="https://raw.github.com/aral/fork-me-on-github-retina-ribbons/master/images-after-imageoptim/fork-me-right-grey@2x.png" alt="Fork me" width="149" height="149"></a>
<div id="scroll-content">
<div id="validate-js">
<div class="header"><h1>Validate.js</h1></div>
<p>
Validate.js provides a declarative way of validating javascript objects.
</p>
<p>
The project can be found on <a href="https://github.com/ansman/validate.js">GitHub</a>
where you can also find our <a href="https://github.com/ansman/validate.js/issues">issue tracker</a>.
There is also a <a href="https://travis-ci.org/ansman/validate.js">Travis project</a>
used for testing and the <a href="docs/validate.html">annotated source</a>.
</p>
<p class="notes">
Validate.js is an open source component of <a href="https://www.wrapp.com">Wrapp</a>
and is licensed under <a href="LICENSE.txt">the MIT license</a>.
</p>
<h2>Downloads & Dependencies</h2>
<div class="download">
<a class="btn btn-default" download href="validate.js">Development version (0.4.0)</a>
<div class="info">
<span class="details">24KB, uncompressed and plenty of comments</span>
</div>
</div>
<div class="download">
<a class="btn btn-primary" download href="validate.min.js">Production version (0.4.0)</a>
<div class="info">
<span class="details">3.1KB, minified and gzipped</span><br>
<a download href="validate.min.map">(Source map)</a>
</div>
</div>
<div class="download">
<a class="btn btn-danger" download href="https://raw.github.com/ansman/validate.js/master/validate.js">Bleeding edge</a>
<div class="info badges">
<span class="details">Might not be 100% stable</span><br>
<a href="https://travis-ci.org/ansman/validate.js">
<img src="https://travis-ci.org/ansman/validate.js.png?branch=master" height="19">
</a>
<a href="https://coveralls.io/r/ansman/validate.js">
<img src="https://coveralls.io/repos/ansman/validate.js/badge.png?branch=master" alt="Coverage Status" />
</a>
</div>
</div>
<p class="dependencies">
There are no required external dependencies but the default parser and
formatter for the datetime and date validator requires <a href="http://arshaw.com/xdate/">XDate</a> or
<a href="http://momentjs.com/">moment.js</a>
</p>
</div>
<div id="overview">
<h2>Overview</h2>
<p>
There are already many validation libraries out there today but most of them
are very tightly coupled to a language or framework.
</p>
<p>
The goal of validate.js is to provide a cross framework and cross language
way of validating data. The validation constraints can be declared in JSON
and shared between clients and the server. Python validation is planned
so is Clojure.
</p>
<p>
<b>Important!</b>
One thing that is a bit unorthodox is that most validators will consider
<code>null</code> and <code>undefined</code> valid values. So for
example adding a constraint of at least 6 characters will be like saying
<i>If the attribute is given it must be at least 6 characters</i>.<br>
This differs from example Ruby on Rails where validators instead have
the <code>allow_nil</code> option. I find it quite common that you
want to have constraints on an optional attribute.
</p>
<div id="supported-runtimes">
<h3>Supported runtimes</h3>
<p>
Validate.js works with any ECMAScript 5.1 runtime which means it works in
both the browser and in node.js
</p>
<p>
All modern browsers are supported (IE9+, Firefox 3+, Opera 10.5+, Safari 4+).<br>
IE8 support can likely be achived by polyfilling the following functions:
</p>
<ul>
<li><code>Array.prototype.indexOf</code></li>
</ul>
</div>
<div id="acknowledgements">
<h3>Acknowledgements</h3>
<ul>
<li>The design of these docs pages have been heavily inspired by <a href="http://backbonejs.org/">backbonejs.org</a>.</li>
<li>All the validators have been inspired by <a href="http://edgeguides.rubyonrails.org/active_record_validations.html">Rails' validators</a>.</li>
</ul>
</div>
</div>
<div id="constraints">
<h2>Constraints</h2>
<p class="description">The constraints have the following format</p>
<pre class="json"><code>{
<attribute>: {
<validator name>: <validator options>
}
}</code></pre>
<p class="description">
Unless otherwise specified you can always specify the <b>message</b>
option to customize the message returned if the validator doesn't pass.
Just remember to not include the attribute name since it's automatically
prepended to the error message.
</p>
<p class="description">
Sometimes it's nice to be able validate field differently depending
on the input itself.
validate.js allows the validators object and validator options to be
a function that should return the constraints/options:
</p>
<pre class="javascript"><code>var constraints = {
creditCardNumber: {
presence: true,
format: {
pattern: /^(34|37|4|5[1-5]).*$/,
message: "must be a valid Amex, Visa or Mastercard number"
},
length: function(value, attributes, attributeName) {
if (value) {
// Amex
if ((/^(34|37).*$/).test(value)) return {is: 15};
// Visa, Mastercard
if ((/^(4|5[1-5]).*$/).test(value)) return {is: 16};
}
// Unknown card, don't validate length
return false;
}
},
creditCardZip: function(value, attributes, attributeName) {
if (!(/^(34|37).*$/).test(attributes.creditCardNumber)) return null;
return {
presence: true,
length: {is: 5}
};
}
};
validate({creditCardNumber: "4"}, constraints);
// => {"creditCardNumber": ["Credit card number is the wrong length (should be 16 characters)"]}
validate({creditCardNumber: "4242424242424242"}, constraints);
// => undefined
validate({creditCardNumber: "340000000000000"}, constraints);
// => {"creditCardZip": ["Credit card zip can't be blank"]}</code></pre>
<p class="description">
If you don't want to give any options to a validator you may pass
<code>true</code> instead of an empty object. The validator will not
be run if the options are falsy.
</p>
<p class="notes">
<b>Important!</b> Most validators consider <code>null</code> and
<code>undefined</code> valid values so make sure you use the
<code>presence</code> validator on attributes that are required.
</p>
</div>
<div id="validate">
<h2>Validate function</h2>
<div class="signature">
<b>validate</b>
<code>validate(attributes, constraints, [options])</code>
</div>
<p class="description">
Validates the <b>attributes</b> object against the <b>constraints</b>.<br>
The <b>attributes</b> must be a plain object, things like backbone models
etc are not supported.<br>
For the format of the <b>constraints</b> see the <a href="#constraints">constraints section</a>.
</p>
<p class="description">
If there are no errors nothing is returned. Otherwise an object in this
format is returned: <code>{<attribute>: [<error>, <error>, ...]}</code>
</p>
<p class="description">
Since validators don't include the argument name in the error message
the validate function prepends it for them. This behaviour can be
disabled by setting the <b>fullMessages</b> option to <code>false</code>.
</p>
<p class="description">
If you need an error not to be prefixed by the attribute add a leading
<code>^</code> to the error and it won't be prepended. If you need to
have a leading <code>^</code> but want the prefixing just write <code>\^</code>.
</p>
<p class="description">
If you want to customize how the attribute names are prettified you
can just override the <code>validate.prettify</code> to your liking.
</p>
<p class="description">
There is also a <b>flatten</b> option which, if <code>true</code>, returns a flat
array instead of an object.
</p>
<pre class="javascript"><code>var constraints = {
username: {presence: true},
password: {
presence: true,
length: {
minimum: 6,
message: "must be at least 6 characters"
}
}
};
validate({password: "bad"}, constraints);
// => {
// "username": ["Username can't be blank"],
// "password": ["Password must be at least 6 characters"]
// }
validate({username: "nicklas", password: "better"}, constraints);
// => undefined
validate({password: "better"}, constraints, {fullMessages: false})
// => {"username": ["can't be blank"]}
validate({}, constraints, {flatten: true})
// => ["Username can't be blank", "Password can't be blank"]
validate({}, {username: {presence: {message: "^You must pick a username"}}});
// => {"username": ["You must pick a username"]}
</code></pre>
<div id="validate-async">
<h3>Async validation</h3>
<div class="signature">
<b>validate.async</b>
<code>validate.async(attributes, constraints, [options])</code>
</div>
<p class="description">
Even though none of the built in validators are async it is sometimes
useful to have async validations. One example would be to check if
a username is already used by asking the server.
</p>
<p class="description">
Validate.js supports async validations through the <code>validate.async</code>
function. It has the same signature as the regular validation function
and accepts the same options.
</p>
<p class="description">
<code>validate.async</code> returns a <a href="http://www.html5rocks.com/en/tutorials/es6/promises/" target="_blank">Promise</a>
that is resolved if the validation passes and is rejected if the
validation failed, passing the errors as the first argument.<br>
The errors has the same format as the errors from the regular validation function.
</p>
<p class="description">
The errors object will be an instance of <b>validate.ValidationErrors</b>
to be able to differentiate between coding errors and validation
errors.
</p>
<p class="description">
You can use the async validate function even if no validations
are async, it still returns a promise. You can not, however, use
the regular function with async validations.
</p>
<p class="description">
Any A+ type promise can be used, the following are supported out
of the box (in order of precedence):
</p>
<ul>
<li>ES6 promises (or the <a href="https://github.com/jakearchibald/ES6-Promises" target="_blank">polyfill version</a>)</li>
<li><a href="https://github.com/tildeio/rsvp.js" target="_blank">RSVP.js</a></li>
<li><a href="https://github.com/cujojs/when" target="_blank">when</a></li>
<li><a href="http://documentup.com/kriskowal/q/" target="_blank">Q</a></li>
</ul>
<p class="description">
Validate.js looks for the promises in the global scope first and
if it can't find it, it tries to import them using the <code>require</code>
function if it exists. This means that AMD is supported but you will
need to make sure that the implementation you want to use is loaded
before you use the async function.
</p>
<p class="description">
You can easily use any other A+ compatible
Promise by simply setting <code>validate.Promise</code> to a function
that accepts the promise callback and returns the created promise.<br>
<em>Please note that jQuery's promise implementation is not A+ compatible and will not work.</em>
</p>
<p class="description">Example:</p>
<pre class="javascript"><code>var success = function() {
alert("The validations passed");
}
, error = function(errors) {
alert(JSON.stringify(errors, null, 2));
}
, constraints = {name: {presence: true}};
// Will call the success function
validate.async({name: "Nicklas"}, constraints).then(success, error);
// Will call the error function
validate.async({}, constraints).then(success, error);
// Supporting another promise implementation, in this case we'll always use
// the ES6 promise
validate.Promise = function(callback) {
return new Promise(callback);
};</code></pre>
</div>
<div id="validate-nested">
<h3>Nested validation</h3>
<p class="description">
Validate.js also has limited support for nested objects (objects
within objects) using the dot notation.
</p>
<p class="description">
The implementation is fairly basic and doesn't do anything clever
with the messages. It doesn't support things like only validating a
sub key if the parent key is present so for more advanced validations
multiple validation schemas are recommended.
</p>
<pre class="javascript"><code>var constraints = {
"addresses.shipping": {
presence: true
},
"addresses.shipping.street": {
format: {
// Must be numbers followed by a name
pattern: "^[0-9]+ .+$",
message: "^The street for the shipping address must be a valid street name"
}
}
};
validate({}, constraints);
// => {"addresses.shipping": ["Addresses shipping can't be blank"]}
validate({addresses: {shipping: {street: "Foobar"}}}, constraints);
// => {"addresses.shipping.street": ["The street for the shipping address must be a valid street name"]}
validate({"foo.bar": 3}, {"foo\\.bar": {numericality: {even: true}}});
// => {"foo\.bar": ["Foo bar must be even"]}
</code></pre>
</div>
<div id="validate-default-options">
<h3>Default options</h3>
<p class="description">
Both the <code>validate</code>, <code>validate.async</code> as well
as all validators support specifying default options by setting
the <code>options</code> property on the respective function or
validator.
</p>
<p class="description">
Most validators allow you to specify default messages in addition
to default options, refer to the documentation for the individual
validators for information on how to do this.
</p>
<pre class="javascript"><code>var constraints = {
name: {
presence: true
}
};
validate.options = {flatten: true};
validate.async.options = {flatten: true};
validate.validators.presence.options = {message: "can't be empty"};
// The default options will be used for both the
// validator and the validate function
validate({}, constraints);
// => ["Name can't be empty"]
// The default options are not used if the constraints options are falsy
validate({flatten: false}, {});
// => undefined</code></pre>
</div>
</div>
<div id="custom-validator">
<h2>Writing your own validator</h2>
<p class="description">
Writing your own validator is super simple! Just add it to the
<code>validate.validators</code> object and it will be automatically
picked up.
</p>
<p class="description">
The validator receives the following arguments:
</p>
<ol>
<li><b>value</b> - The value exactly how it looks in the attribute object.</li>
<li>
<b>options</b> - The options for the validator. Guaranteed to not
be <code>null</code> or <code>undefined</code>.
</li>
<li>
<b>key</b> - The attribute name.
</li>
<li>
<b>attributes</b> - The entire attributes object.
</li>
</ol>
<p class="description">
If the validator passes simply return <code>null</code> or <code>undefined</code>.
Otherwise return a string or an array of strings containing the
error message(s).<br>
Make sure not to append the key name, this will be done automatically.
</p>
<pre class="javascript"><code>validate.validators.custom = function(value, options, key, attributes) {
console.log(value);
console.log(options);
console.log(key);
console.log(attributes);
return "is totally wrong";
};
// Will log:
// - "some value"
// - "some options"
// - "foo"
// - {"foo": "some value"}
validate({foo: "some value"}, {foo: {custom: "some options"}});
// => {foo: ["Foo is totally wrong"]}</code></pre>
<div id="custom-validator-async">
<h3>Writing an async validator</h3>
<p class="description">
Async validators are equal to a regular one in every way except
in what they return. An async validator should return a promise
(usually a <code>validate.Promise</code> instance).
</p>
<p class="description">
The promise should be resolved if the validation passed and rejected
if it fails giving the message as the first argument:
</p>
<pre class="javascript"><code>validate.validators.myAsyncValidator = function(value) {
return validate.Promise(function(resolve, reject) {
setTimeout(function() {
if (value === "foo") resolve();
else reject("is not foo");
}, 100);
});
};
var constraints = {name: {myAsyncValidator: true}}
, success = alert.bind(this, "The validations passed")
, error = function(errors) {
alert(JSON.stringify(errors, null, 2));
};
// Will call the success callback
validate.async({name: "foo"}, constraints).then(success, error);
// Will call the error callback with {name: ["Name is not foo"]} as the first argument
validate.async({name: "bar"}, constraints).then(success, error);</code></pre>
</div>
</div>
<div id="validators">
<h2>Validators</h2>
<div id="validators-presence">
<div class="signature"><b>presence</b></div>
<p class="description">
The presence validator validates that the value isn't empty.
This validator will probably the most used one, it corresponds to
HTML5's required attribute.<br>
You can use the <b>message</b> option to customize the message. The
default message is <i>can't be blank</i> and can be changed by
setting <code>validate.validators.presence.message</code>.
</p>
<p class="description">
These are the values that are considered empty:
</p>
<ul>
<li><code>null</code></li>
<li><code>undefined</code></li>
<li><code>[]</code> (empty objects)</li>
<li><code>{}</code> (empty arrays)</li>
<li><code>""</code> (empty string)</li>
<li><code>" "</code> (whitespace only string)</li>
</ul>
<p class="notes">
<b>Important!</b> All other values are considered valid (including functions)!
</p>
<pre class="javascript"><code>validate({}, {username: {presence: true}})
// => {"username": ["Username can't be blank"]}
validate({username: "ansman"}, {username: {presence: true}})
// => undefined
validate({}, {username: {presence: {message: "is required"}}})
// => {"username": ["Username is required"]}
validate.validators.presence.message = "is required";
validate({}, {username: {presence: true}});
// => {"username": ["Username is required"]}
</code></pre>
</div>
<div id="validators-length">
<div class="signature"><b>length</b></div>
<p class="description">
The length validator will check the length of a string.<br>
Any object with the <code>length</code> property can be validated
but all the default error messages refers to strings so make sure
you override them if you plan on validating arrays using this.
</p>
<p class="description">
You may specify the following length constraints:
</p>
<dl class="dl-horizontal">
<dt>is</dt>
<dd>
The value has to have exactly this length. The default error is
<i>is the wrong length (should be %{count} characters)</i>
</dd>
<dt>minimum</dt>
<dd>
The value cannot be shorter than this value. The default error is
<i>is too short (minimum is %{count} characters)</i>
</dd>
<dt>maximum</dt>
<dd>
The value cannot be longer than this value. The default error is
<i>is too long (maximum is %{count} characters)</i>
</dd>
</dl>
<p class="description">
You can specify the error message using the <b>wrongLength</b>,
<b>tooShort</b> and <b>tooLong</b> options. The default values are
<i>is the wrong length (should be %{count} characters)</i>,
<i>is too short (minimum is %{count} characters)</i> and
<i>is too long (maximum is %{count} characters)</i> respectively.<br>
<br>
As you may have noticed you can use <code>%{count}</code> as a placeholder
for the actual constraint and it will be replaced for you.
</p>
<p class="description">
The default messages can also be changed by setting the following
attributes on <code>validate.validators.length</code>:
</p>
<ul>
<li><code>notValid</code></li>
<li><code>tooLong</code></li>
<li><code>tooShort</code></li>
<li><code>wrongLength</code></li>
</ul>
<p class="description">
You can also use the <b>message</b> as the message for all errors
(this overrides any other custom errors).
</p>
<p class="description">
Per default the number of characters are counted (using the <code>length</code>
property), if you want to count something else you can specify the
<b>tokenizer</b> option which should be a function that takes a single
argument (the value) and the returns a value that should be used when
counting.<br>
<br>
The tokenizer will never be called with <code>nil</code> or <code>undefined</code>
as an argument.
</p>
<p class="description">
Once important thing to note is that the value needs to have a numeric
value for the <code>length</code> property or the message <i>has an incorrect length</i>
is returned.<br>
An error is also logged to the console since this is considered a
coding error.
</p>
<pre class="javascript"><code>var constraints = {
key1: {length: {is: 3}},
key2: {length: {minimum: 20}},
key3: {length: {maximum: 3}},
key4: {
length: {
minimum: 3,
tooShort: "needs to have %{count} words or more",
tokenizer: function(value) {
return value.split(/\s+/g);
}
}
}
};
validate({}, constraints);
// => undefined
// This is because nil and undefined are valid values.
// Use the presence validator if you don't want to allow empty values.
var values = {
key1: "wrong length",
key2: "too short",
key3: "too long",
key4: "too short"
};
validate(values, constraints);
// => {
// "key1": ["Key1 is the wrong length (should be 3 characters)"],
// "key2": ["Key2 is too short (minimum is 20 characters)"],
// "key3": ["Key3 is too long (maximum is 3 characters)"],
// "key4": ["Key4 needs to have 3 words or more"]
// }</code></pre>
</div>
<div id="validators-numericality">
<div class="signature"><b>numericality</b></div>
<p class="description">
The numericality validator will only allow numbers.
Per default strings are coerced to numbers using the <code>+</code>
operator. If this is not desirable you can set the <b>noStrings</b>
option to <code>false</code> to disable this behaviour.
</p>
<p class="description">
The following constraints can be applied:
</p>
<dl class="dl-horizontal">
<dt>onlyInteger</dt>
<dd>Real numbers won't be allowed. The error message is <i>must be an integer</i></dd>
<dt>greaterThan</dt>
<dd>The input has to be greater than this value. The error message is <i>must be greater than %{count}</i></dd>
<dt>greaterThanOrEqualTo</dt>
<dd>The input has to be at least this value. The error message is <i>must be greater than or equal to %{count}</i></dd>
<dt>equalTo</dt>
<dd>The input has to be exactly this value. The error message is <i>must be equal to %{count}</i></dd>
<dt>lessThanOrEqualTo</dt>
<dd>The input can be this value at the most. The error message is <i>must be less than or equal to %{count}</i></dd>
<dt>lessThan</dt>
<dd>The input has to be less than this value. The error message is <i>must be less than %{count}</i></dd>
<dt>odd</dt>
<dd>The input has to be odd. The error message is <i>must be odd</i></dd>
<dt>even</dt>
<dd>The input has to be even. The error message is <i>must be even</i></dd>
</dl>
<p class="description">
If you want a custom error message you may specify it using the
<b>message</b> option or by settings one of the following default
messages on the <code>validate.validators.numericality</code> object:
</p>
<ul>
<li><code>notValid</code></li>
<li><code>notInteger</code></li>
<li><code>notGreaterThan</code></li>
<li><code>notGreaterThanOrEqualTo</code></li>
<li><code>notEqualTo</code></li>
<li><code>notLessThan</code></li>
<li><code>notLessThanOrEqualTo</code></li>
<li><code>notOdd</code></li>
<li><code>notEven</code></li>
</ul>
<pre class="javascript"><code>// null and undefined are valid values regardless of the options
validate({}, {duration: {numericality: true}});
//= > undefined
validate({duration: "foobar"}, {duration: {numericality: true}});
// => {"duration": ["Duration is not a number"]}
validate({duration: "3"}, {duration: {numericality: true}});
// => undefined
validate({duration: "3"}, {duration: {numericality: {noStrings: true}}});
// => {"duration": ["Duration is not a number"]}
var constraints = {
duration: {
numericality: {
onlyInteger: true,
greaterThan: 0,
lessThanOrEqualTo: 30,
even: true
}
}
};
validate({duration: 3.14}, constraints);
// => {"duration": ["Duration must be an integer"]}
validate({duration: 4711}, constraints);
// => {
// "duration": [
// "Duration must be less than or equal to 30",
// "Duration must be even"
// ]
// }</code></pre>
</div>
<div id="validators-datetime">
<div class="signature"><b>datetime</b></div>