forked from ansman/validate.js
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.html
3065 lines (2871 loc) · 118 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, initial-scale=1, maximum-scale=1">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.5/css/bootstrap.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/8.8.0/styles/default.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/8.8.0/styles/github.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/8.8.0/highlight.min.js"></script>
<script>hljs.initHighlightingOnLoad();</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bluebird/2.10.2/bluebird.min.js" async></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.10.6/moment.min.js" async></script>
<script src="validate.js" async></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);
}
header {
z-index: 10;
position: fixed;
top: 0;
left: 0;
width: 100%;
}
header .title {
font-size: 25px;
line-height: 50px;
border-bottom: none;
display: inline-block;
margin: 0;
padding: 0;
display: none;
}
#menu-button {
display: none;
width: 30px;
border: none;
background: none;
padding: 0;
margin: 15px 10px;
-webkit-transform: translateZ(0);
}
#menu-button .bar {
width: 100%;
height: 4px;
background-color: black;
border-radius: 1px;
margin-top: 4px;
}
#menu-button .bar:first-child {
margin-top: 0;
}
#sidebar {
background-color: #F7F5FA;
box-sizing: border-box;
padding-top: 10px;
padding-left: 10px;
overflow-y: scroll;
-webkit-overflow-scrolling: touch;
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: 820px;
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;
}
.banner 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, #utilities > div {
padding: 10px 0px;
}
#changelog h3 {
font-size: 14px;
}
#changelog h3 .version {
font-size: 18px;
}
@media (max-width: 945px) {
body {
padding-left: 0;
}
#fork-me {
display: none;
}
header {
background-color: white;
height: 50px;
border-bottom: 1px solid rgba(0, 0, 0, 0.1);
-webkit-box-shadow: 0px 2px black;
-moz-box-shadow: 0px 2px black;
box-shadow: 0px 0px 20px rgba(0, 0, 0, 0.1);
}
header #menu-button, header .title {
display: inline-block;
}
.banner {
text-align: center;
}
.download {
text-align: center;
}
.download .btn {
width: 100%;
margin-bottom: 3px;
}
.banner h1 {
font-size: 40px;
margin-top: 0;
}
#sidebar {
left: -299px;
top: 50px;
padding-top: 10px;
z-index: 10;
-webkit-transition: left 250ms ease-in;
}
.sidebar-shown #sidebar {
left: 0;
-webkit-transition-timing-function: ease-out;
}
#content {
margin-top: 50px;
padding-top: 20px;
margin-left: 0;
overflow: hidden;
}
#scroll-content {
min-width: 0;
padding: 10px;
}
code {
white-space: normal;
}
pre {
overflow: scroll;
-webkit-overflow-scrolling: touch;
}
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('set', 'anonymizeIp', true);
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="#downloads">Downloads</a></li>
<li><a href="#installing">Installing</a></li>
<li><a href="#dependencies">Dependencies</a></li>
<li>
<a href="#overview">Overview</a>
<ul>
<li><a href="#supported-runtimes">Supported runtimes</a></li>
<li><a href="#examples">Examples</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-single">Single value validation</a></li>
<li><a href="#validate-nested">Nested validation</a></li>
<li><a href="#validate-default-options">Default options</a></li>
<li><a href="#validate-error-formatting">Error formatting</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-date">Date</a></li>
<li><a href="#validators-datetime">Datetime</a></li>
<li><a href="#validators-email">Email</a></li>
<li><a href="#validators-equality">Equality</a></li>
<li><a href="#validators-exclusion">Exclusion</a></li>
<li><a href="#validators-format">Format</a></li>
<li><a href="#validators-inclusion">Inclusion</a></li>
<li><a href="#validators-length">Length</a></li>
<li><a href="#validators-numericality">Numericality</a></li>
<li><a href="#validators-presence">Presence</a></li>
<li><a href="#validators-type">Type</a></li>
<li><a href="#validators-url">URL</a></li>
</ul>
</li>
<li>
<a href="#utilities">Utilities</a>
<ul>
<li><a href="#utilities-capitalize">capitalize</a></li>
<li><a href="#utilities-clean-attributes">cleanAttributes</a></li>
<li><a href="#utilities-collect-form-values">collectFormValues</a></li>
<li><a href="#utilities-contains">contains</a></li>
<li><a href="#utilities-extend">extend</a></li>
<li><a href="#utilities-format">format</a></li>
<li><a href="#utilities-get-deep-object-value">getDeepObjectValue</a></li>
<li><a href="#utilities-is-array">isArray</a></li>
<li><a href="#utilities-is-boolean">isBoolean</a></li>
<li><a href="#utilities-is-date">isDate</a></li>
<li><a href="#utilities-is-defined">isDefined</a></li>
<li><a href="#utilities-is-dom-element">isDomElement</a></li>
<li><a href="#utilities-is-empty">isEmpty</a></li>
<li><a href="#utilities-is-function">isFunction</a></li>
<li><a href="#utilities-is-hash">isHash</a></li>
<li><a href="#utilities-is-integer">isInteger</a></li>
<li><a href="#utilities-is-number">isNumber</a></li>
<li><a href="#utilities-is-object">isObject</a></li>
<li><a href="#utilities-is-promise">isPromise</a></li>
<li><a href="#utilities-is-string">isString</a></li>
<li><a href="#utilities-prettify">prettify</a></li>
<li><a href="#utilities-result">result</a></li>
</ul>
</li>
<li>
<a href="#changelog">Changelog</a>
<ul>
<li><a href="https://github.com/ansman/validate.js/releases/tag/0.13.1">0.13.1</a></li>
<li><a href="#changelog-0-12-0">0.12.0</a></li>
<li><a href="#changelog-0-11-1">0.11.1</a></li>
<li><a href="#changelog-0-11-0">0.11.0</a></li>
<li><a href="#changelog-0-10-0">0.10.0</a></li>
<li><a href="#changelog-0-9-0">0.9.0</a></li>
<li><a href="#changelog-0-8-0">0.8.0</a></li>
<li><a href="#changelog-0-7-1">0.7.1</a></li>
<li><a href="#changelog-0-7-0">0.7.0</a></li>
<li><a href="#changelog-0-6-1">0.6.1</a></li>
<li><a href="#changelog-0-6-0">0.6.0</a></li>
<li><a href="#changelog-0-5-0">0.5.0</a></li>
<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>
<header>
<button id="menu-button">
<div class="bar"></div>
<div class="bar"></div>
<div class="bar"></div>
</button>
<div class="title">Validate.js</div>
</header>
<div id="content">
<div id="scroller">
<a id="fork-me" href="https://github.com/ansman/validate.js"><img src="https://raw.githubusercontent.com/aral/fork-me-on-github-retina-ribbons/master/images-after-imageoptim/[email protected]" alt="Fork me" width="149" height="149"></a>
<div id="scroll-content">
<div id="validate-js">
<div class="banner"><h1>Validate.js</h1></div>
<p>
Validate.js provides a declarative way of validating javascript objects.
</p>
<p>
It is unit tested with 100% code coverage and can be considered fit
for production.
</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" target="_blank">Travis project</a>
used for testing,
a <a href="https://coveralls.io/r/ansman/validate.js" target="_blank">Coveralls project</a>
used to code coverage
as well as 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 id="downloads">Downloads</h2>
<div class="download">
<a class="btn btn-default" download href="validate.js">Development version (0.13.1)</a>
<div class="info">
<span class="details">38KB, uncompressed and plenty of comments</span>
</div>
</div>
<div class="download">
<a class="btn btn-primary" download href="validate.min.js">Production version (0.13.1)</a>
<div class="info">
<span class="details">5.05KB, 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" target="_blank">
<img src="https://travis-ci.org/ansman/validate.js.svg?branch=master" alt="Build Status" width="90" height="20">
</a>
<a href="https://coveralls.io/r/ansman/validate.js" target="_blank">
<img src="https://coveralls.io/repos/ansman/validate.js/badge.svg?branch=master" alt="Coverage Status" width="106" height="20"/>
</a>
</div>
</div>
<div id="installing">
<h2>Installing</h2>
<b>Browser/CDN</b>
<pre><code class="html"><script src="//cdnjs.cloudflare.com/ajax/libs/validate.js/0.13.1/validate.min.js"></script></code></pre>
<b>Require.js/AMD</b>
<pre><code class="javascript">require(["validate.js"], function(validate) {
// ...
});</code></pre>
<b>npm/node.js</b>
<pre><code class="bash">$ npm install --save validate.js</code></pre>
<pre><code class="javascript">var validate = require("validate.js");</code></pre>
<b>Bower</b>
<pre><code class="bash">$ bower install --save validate.js</code></pre>
<b>Component</b>
<pre><code class="bash">$ component install ansman/validate.js</code></pre>
</div>
<h2 id="dependencies">Dependencies</h2>
<p class="dependencies">
There are no required external dependencies at all! Though for the
datetime and date validator to you need to specify a parse and format
function and for that you most likely will want to use a library,
moment.js is highly recommended.
</p>
<p class="dependencies">
If you want to use async validation you need to use a runtime that
supports <a href="http://www.html5rocks.com/en/tutorials/es6/promises/" target="_blank">Promises</a>.<br>
You can tell validate.js to use any A+ compatible promise implemention
like this:
</p>
<pre><code class="javascript">// Simply set validate.Promise to be the promise constructor
// RSVP works
validate.Promise = RSVP.Promise;
// and Q.js too
validate.Promise = Q.Promise;</code></pre>
</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.
</p>
<p>
<b>Important!</b>
One thing that is a bit unorthodox is that most validators will
consider undefined values (<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.<br>
</p>
<p>
One core value of this library is that nothing should be private or
inaccessable. If you want to modify which values are considered
empty for example you can simply overwrite
<code>validate.isEmpty</code>, this way you don't have to wait for
a pull request to be accepted or create a fork.
</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+, Chrome).</p>
</div>
<div id="examples">
<h3>Examples</h3>
<p>
You can find some basic examples <a href="examples.html">included in the project</a>.
</p>
<p>
They are meant to give a feeling for how to use the library and
should not be considered production ready code.
</p>
<p>
The native HTML form validate has been disabled in a demo purpose
so that you may see how validate.js works in action.
</p>
</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><code class="json">{
<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">
The message can also be a function which will be called to retrieve
the message, besides this it is treated like a normal message (the
attribute name is prepended etc).<br>
If the message is not a function and not a string it is simply
returned as is.
</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><code class="javascript">var constraints = {
creditCardNumber: {
presence: true,
format: {
pattern: /^(34|37|4|5[1-5]).*$/,
message: function(value, attribute, validatorOptions, attributes, globalOptions) {
return validate.format("^%{num} is not a valid credit card number", {
num: value
});
}
},
length: function(value, attributes, attributeName, options, constraints) {
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, options, constraints) {
if (!(/^(34|37).*$/).test(attributes.creditCardNumber)) return null;
return {
presence: {message: "is required when using AMEX"},
length: {is: 5}
};
}
};
validate({creditCardNumber: "4"}, constraints);
// => {"creditCardNumber": ["Credit card number is the wrong length (should be 16 characters)"]}
validate({creditCardNumber: "9999999999999999"}, constraints);
// => {"creditCardNumber": ["9999999999999999 is not a valid credit card number"]}
validate({creditCardNumber: "4242424242424242"}, constraints);
// => undefined
validate({creditCardNumber: "340000000000000"}, constraints);
// => {"creditCardZip": ["Credit card zip is required when using AMEX"]}</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 undefined values
(<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 or a form element,
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 the <b>attributes</b> objects is an HTML/DOM/jQuery element
<a href="#utilities-collect-form-values"><code>collectFormValues</code></a>
is called before validating.
</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 include <code>%{value}</code> in the error message it will be
replaced with the actual value. The value is transformed using
<code>validate.stringifyValue</code> (which per default just calls
<code>validate.prettify</code>) but it can be overidden to customize
the formatting.
</p>
<p class="description">
If you want to customize how the attribute names are prettified you
can either override the <code>validate.prettify</code> function
or you can give a function as the <b>prettify</b> option.
</p>
<p class="description">
There is also a <b>format</b> option. To see more details about this
option see
<a href="#validate-error-formatting">the section about it</a>.
</p>
<pre><code class="javascript">var constraints = {
username: {
presence: true,
exclusion: {
within: ["nicklas"],
message: "'%{value}' is not allowed"
}
},
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: "nick", password: "better"}, constraints);
// => undefined
validate({username: "nicklas", password: "better"}, constraints);
// => {"username": ["Username 'nicklas' is not allowed"]}
validate({password: "better"}, constraints, {fullMessages: false});
// => {"username": ["can't be blank"]}
validate({}, constraints, {format: "flat"});
// => ["Username can't be blank", "Password can't be blank"]
validate({username: "nicklas", password: "bad"}, constraints, {format: "detailed"});
// => [
// {
// "attribute": "username",
// "value": "nicklas",
// "validator": "exclusion",
// "globalOptions": {
// "format": "detailed"
// },
// "attributes": {
// "username": "nicklas",
// "password": "bad"
// },
// "options": {
// "within": [
// "nicklas"
// ],
// "message": "'%{value}' is not allowed"
// },
// "error": "Username 'nicklas' is not allowed"
// },
// {
// "attribute": "password",
// "value": "bad",
// "validator": "length",
// "globalOptions": {
// "format": "detailed"
// },
// "attributes": {
// "username": "nicklas",
// "password": "bad"
// },
// "options": {
// "minimum": 6,
// "message": "must be at least 6 characters"
// },
// "error": "Password must be at least 6 characters"
// }
// ]
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.
</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">
Besides accepting all options as the non async validation function
it also accepts two additional options; <b>cleanAttributes</b> which,
unless <code>false</code>, makes <code>validate.async</code>
call <a href="#utilities-clean-attributes"><code>validate.cleanAttributes</code></a>
before resolving the promise and <b>wrapErrors</b> which can be
a function or constructor that will be called with the errors,
options, attributes and constraints if an error occurs. This allows
you to define a better way of catching validation errors.
</p>
<p class="description">
If an <code>Error</code> is thrown from an async validator the
argument passed to the rejection handler will be that error. This
allows you to differentiate from 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, just override <code>validate.Promise</code>
with the constructor of the new Promise implementation.
</p>
<p class="description">
Validate.js will try to use the global Promise function if it exists
otherwise it will throw an exception when using <code>validate.async</code>
</p>
<p class="notes">
Please note that jQuery's promise implementation is not A+
compatible and will not work.
</p>
<p class="description">Example:</p>
<pre><code class="javascript">function success(attributes) {
console.log("Success!", attributes);
}
function error(errors) {
if (errors instanceof Error) {
// This means an exception was thrown from a validator
console.err("An error ocurred", errors);
} else {
console.log("Validation errors", errors);
}
}
var constraints = {
name: {
presence: true
},
// This is so the country doesn't get removed when cleaning the attributes
country: {}
};
var attributes = {
name: "Nicklas",
country: "Sweden",
someMaliciousAttribute: "scary value"
};
// Will call the success function and log {
// name: "Nicklas",
// country: "Sweden"
// }
validate.async(attributes, constraints).then(success, error);
// Will call the error function
validate.async({}, constraints).then(success, error);
function ValidationErrors(errors, options, attributes, constraints) {
Error.captureStackTrace(this, this.constructor);
this.errors = errors;
this.options = options;
this.attributes = attributes;
this.constraints = constraints;
}
ValidationErrors.prototype = new Error();
// This isn't supported by the ES6 promises
validate.async({}, constraints, {wrapErrors: ValidationErrors})
.then(success)
.catch(ValidationErrors, function(error) {
// Handle the validation errors
console.log("ValidationErrors", error);
})
.catch(function(error) {
// Handle other errors;
console.log("SystemError", error);
});
// Supporting another promise implementation (RSVP in this case)
validate.Promise = RSVP.Promise;</code></pre>
</div>
<div id="validate-single">
<h3>Single value validation</h3>
<div class="signature">
<b>validate.single</b>
<code>validate.single(value, constraints, [options])</code>
</div>
<p class="description">
Sometimes you only want to validate a single value against some
constraints and using the normal validate function is quite
verbose so there is a shorthand for this.
</p>
<p class="description">
It does little more than proxying the call to the main validation
function but with the value wrapped in an object and the options
<b>fullMessages</b> and <b>format</b> set to <code>"flat"</code>.
This is because there is no name which means it can't produce
full messages.
</p>
<p class="description">
You can use the provided <a href="#utilities-format">format</a>,
<a href="#utilities-capitalize">capitalize</a> and
<a href="#utilities-prettify">prettify</a>
utility functions to append your own name.
</p>
<pre><code class="javascript">validate.single(null, {presence: true, email: true});
// => ["can't be blank"]
validate.single("foo", {presence: true, email: true});
// => ["is not a valid email"]
validate.single("[email protected]", {presence: true, email: true});
// => undefined</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><code class="javascript">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><code class="javascript">var constraints = {
name: {
presence: true
}
};
validate.options = {format: "flat"};
validate.async.options = {format: "flat", cleanAttributes: false};
validate.validators.presence.options = {message: "can't be empty"};