commiting uncommited changes on live site
[weblabels.fsf.org.git] / crm.fsf.org / 20131203 / files / sites / all / modules-old / civicrm / packages / backbone-forms / src / validators.js
1
2 //==================================================================================================
3 //VALIDATORS
4 //==================================================================================================
5
6 Form.validators = (function() {
7
8 var validators = {};
9
10 validators.errMessages = {
11 required: 'Required',
12 regexp: 'Invalid',
13 email: 'Invalid email address',
14 url: 'Invalid URL',
15 match: 'Must match field "{{field}}"'
16 };
17
18 validators.required = function(options) {
19 options = _.extend({
20 type: 'required',
21 message: this.errMessages.required
22 }, options);
23
24 return function required(value) {
25 options.value = value;
26
27 var err = {
28 type: options.type,
29 message: Form.helpers.createTemplate(options.message, options)
30 };
31
32 if (value === null || value === undefined || value === false || value === '') return err;
33 };
34 };
35
36 validators.regexp = function(options) {
37 if (!options.regexp) throw new Error('Missing required "regexp" option for "regexp" validator');
38
39 options = _.extend({
40 type: 'regexp',
41 message: this.errMessages.regexp
42 }, options);
43
44 return function regexp(value) {
45 options.value = value;
46
47 var err = {
48 type: options.type,
49 message: Form.helpers.createTemplate(options.message, options)
50 };
51
52 //Don't check empty values (add a 'required' validator for this)
53 if (value === null || value === undefined || value === '') return;
54
55 if (!options.regexp.test(value)) return err;
56 };
57 };
58
59 validators.email = function(options) {
60 options = _.extend({
61 type: 'email',
62 message: this.errMessages.email,
63 regexp: /^[\w\-]{1,}([\w\-\+.]{1,1}[\w\-]{1,}){0,}[@][\w\-]{1,}([.]([\w\-]{1,})){1,3}$/
64 }, options);
65
66 return validators.regexp(options);
67 };
68
69 validators.url = function(options) {
70 options = _.extend({
71 type: 'url',
72 message: this.errMessages.url,
73 regexp: /^(http|https):\/\/(([A-Z0-9][A-Z0-9_\-]*)(\.[A-Z0-9][A-Z0-9_\-]*)+)(:(\d+))?\/?/i
74 }, options);
75
76 return validators.regexp(options);
77 };
78
79 validators.match = function(options) {
80 if (!options.field) throw new Error('Missing required "field" options for "match" validator');
81
82 options = _.extend({
83 type: 'match',
84 message: this.errMessages.match
85 }, options);
86
87 return function match(value, attrs) {
88 options.value = value;
89
90 var err = {
91 type: options.type,
92 message: Form.helpers.createTemplate(options.message, options)
93 };
94
95 //Don't check empty values (add a 'required' validator for this)
96 if (value === null || value === undefined || value === '') return;
97
98 if (value !== attrs[options.field]) return err;
99 };
100 };
101
102
103 return validators;
104
105 })();