Debian Codegraph @

dojox/validate/check.js

raw symbols SCIP
1 define(["dojo/_base/kernel", "dojo/_base/lang", "./_base"
2 ], function(kernel, lang, validate){
3 kernel.experimental("dojox.validate.check");
4
5 /**
6 FIXME: How much does this overlap with dojox.form.Manager and friends?
7
8 Procedural API Description
9
10 The main aim is to make input validation expressible in a simple format.
11 You define profiles which declare the required and optional fields and any constraints they might have.
12 The results are provided as an object that makes it easy to handle missing and invalid input.
13
14 Usage
15
16 var results = dojox.validate.check(form, profile);
17
18 Profile Object
19
20 var profile = {
21 // filters change the field value and are applied before validation.
22 trim: ["tx1", "tx2"],
23 uppercase: ["tx9"],
24 lowercase: ["tx5", "tx6", "tx7"],
25 ucfirst: ["tx10"],
26 digit: ["tx11"],
27
28 // required input fields that are blank will be reported missing.
29 // required radio button groups and drop-down lists with no selection will be reported missing.
30 // checkbox groups and selectboxes can be required to have more than one value selected.
31 // List required fields by name and use this notation to require more than one value: {checkboxgroup: 2}, {selectboxname: 3}.
32 required: ["tx7", "tx8", "pw1", "ta1", "rb1", "rb2", "cb3", "s1", {"doubledip":2}, {"tripledip":3}],
33
34 // dependant/conditional fields are required if the target field is present and not blank.
35 // At present only textbox, password, and textarea fields are supported.
36 dependencies: {
37 cc_exp: "cc_no",
38 cc_type: "cc_no"
39 },
40
41 // Fields can be validated using any boolean valued function.
42 // Custom validation fields can also return custom error messages.
43 // Function name may also be written as a string (useful when passing form profile via JSON)
44 // Use arrays to specify parameters in addition to the field value.
45 constraints: {
46 field_name1: myValidationFunction,
47 field_name2: [myValidationFunction, additional parameters],
48 field_name3: "myValidationFunction",
49 field_name4: ["myValidationFunction", {"message" : "Value must be an integer. Please try again.", additional parameters}]
50 field_name5: dojox.validate.isInteger,
51 field_name6: [dojox.validate.isValidDate, "YYYY.MM.DD"],
52 field_name7: [dojox.validate.isEmailAddress, false, true] },
53
54 // Confirm is a sort of conditional validation.
55 // It associates each field in its property list with another field whose value should be equal.
56 // If the values are not equal, the field in the property list is reported as Invalid. Unless the target field is blank.
57 confirm: {
58 email_confirm: "email",
59 pw2: "pw1"
60 }
61 };
62
63 Results Object
64
65 isSuccessful(): Returns true if there were no invalid or missing fields, else it returns false.
66 hasMissing(): Returns true if the results contain any missing fields.
67 getMissing(): Returns a list of required fields that have values missing.
68 isMissing(field): Returns true if the field is required and the value is missing.
69 hasInvalid(): Returns true if the results contain fields with invalid data.
70 getInvalid(): Returns a list of fields that have invalid values and custom error messages (optional).
71 isInvalid(field): Returns true if the field has an invalid value.
72
73 */
74
75 validate.check = function(/*HTMLFormElement*/form, /*Object*/profile){
76 // summary:
77 // validates user input of an HTML form based on input profile
78 // description:
79 // returns an object that contains several methods summarizing the results of the validation
80 // form:
81 // form to be validated
82 // profile:
83 // specifies how the form fields are to be validated
84 // {trim:Array, uppercase:Array, lowercase:Array, ucfirst:Array, digit:Array,
85 // required:Array, dependencies:Object, constraints:Object, confirm:Object}
86
87 // Essentially private properties of results object
88 var missing = [];
89 var invalid = [];
90
91 // results object summarizes the validation
92 var results = {
93 isSuccessful: function() {return ( !this.hasInvalid() && !this.hasMissing() );},
94 hasMissing: function() {return ( missing.length > 0 );},
95 getMissing: function() {return missing;},
96 isMissing: function(elemname) {
97 for(var i = 0; i < missing.length; i++){
98 if(elemname == missing[i]){ return true; }
99 }
100 return false;
101 },
102 hasInvalid: function() {return ( invalid.length > 0 );},
103 getInvalid: function() {return invalid;},
104 isInvalid: function(elemname){
105 for(var i = 0; i < invalid.length; i++){
106 if(elemname == invalid[i]){ return true; }
107 }
108 return false;
109 }
110 };
111
112 var _undef = function(name,object){
113 return (typeof object[name] == "undefined");
114 };
115
116 // Filters are applied before fields are validated.
117 // Trim removes white space at the front and end of the fields.
118 if(profile.trim instanceof Array){
119 for(var i = 0; i < profile.trim.length; i++){
120 var elem = form[profile.trim[i]];
121 if(_undef("type", elem) || elem.type != "text" && elem.type != "textarea" && elem.type != "password"){ continue; }
122 elem.value = elem.value.replace(/(^\s*|\s*$)/g, "");
123 }
124 }
125 // Convert to uppercase
126 if(profile.uppercase instanceof Array){
127 for(var i = 0; i < profile.uppercase.length; i++){
128 var elem = form[profile.uppercase[i]];
129 if(_undef("type", elem) || elem.type != "text" && elem.type != "textarea" && elem.type != "password"){ continue; }
130 elem.value = elem.value.toUpperCase();
131 }
132 }
133 // Convert to lowercase
134 if(profile.lowercase instanceof Array){
135 for (var i = 0; i < profile.lowercase.length; i++){
136 var elem = form[profile.lowercase[i]];
137 if(_undef("type", elem) || elem.type != "text" && elem.type != "textarea" && elem.type != "password"){ continue; }
138 elem.value = elem.value.toLowerCase();
139 }
140 }
141 // Uppercase first letter
142 if(profile.ucfirst instanceof Array){
143 for(var i = 0; i < profile.ucfirst.length; i++){
144 var elem = form[profile.ucfirst[i]];
145 if(_undef("type", elem) || elem.type != "text" && elem.type != "textarea" && elem.type != "password"){ continue; }
146 elem.value = elem.value.replace(/\b\w+\b/g, function(word) { return word.substring(0,1).toUpperCase() + word.substring(1).toLowerCase(); });
147 }
148 }
149 // Remove non digits characters from the input.
150 if(profile.digit instanceof Array){
151 for(var i = 0; i < profile.digit.length; i++){
152 var elem = form[profile.digit[i]];
153 if(_undef("type", elem) || elem.type != "text" && elem.type != "textarea" && elem.type != "password"){ continue; }
154 elem.value = elem.value.replace(/\D/g, "");
155 }
156 }
157
158 // See if required input fields have values missing.
159 if(profile.required instanceof Array){
160 for(var i = 0; i < profile.required.length; i++){
161 if(!lang.isString(profile.required[i])){ continue; }
162 var elem = form[profile.required[i]];
163 // Are textbox, textarea, or password fields blank.
164 if(!_undef("type", elem)
165 && (elem.type == "text" || elem.type == "textarea" || elem.type == "password" || elem.type == "file")
166 && /^\s*$/.test(elem.value)){
167 missing[missing.length] = elem.name;
168 }
169 // Does drop-down box have option selected.
170 else if(!_undef("type", elem) && (elem.type == "select-one" || elem.type == "select-multiple")
171 && (elem.selectedIndex == -1
172 || /^\s*$/.test(elem.options[elem.selectedIndex].value))){
173 missing[missing.length] = elem.name;
174 }
175 // Does radio button group (or check box group) have option checked.
176 else if(elem instanceof Array){
177 var checked = false;
178 for(var j = 0; j < elem.length; j++){
179 if (elem[j].checked) { checked = true; }
180 }
181 if(!checked){
182 missing[missing.length] = elem[0].name;
183 }
184 }
185 }
186 }
187
188 // See if checkbox groups and select boxes have x number of required values.
189 if(profile.required instanceof Array){
190 for (var i = 0; i < profile.required.length; i++){
191 if(!lang.isObject(profile.required[i])){ continue; }
192 var elem, numRequired;
193 for(var name in profile.required[i]){
194 elem = form[name];
195 numRequired = profile.required[i][name];
196 }
197 // case 1: elem is a check box group
198 if(elem instanceof Array){
199 var checked = 0;
200 for(var j = 0; j < elem.length; j++){
201 if(elem[j].checked){ checked++; }
202 }
203 if(checked < numRequired){
204 missing[missing.length] = elem[0].name;
205 }
206 }
207 // case 2: elem is a select box
208 else if(!_undef("type", elem) && elem.type == "select-multiple" ){
209 var selected = 0;
210 for(var j = 0; j < elem.options.length; j++){
211 if (elem.options[j].selected && !/^\s*$/.test(elem.options[j].value)) { selected++; }
212 }
213 if(selected < numRequired){
214 missing[missing.length] = elem.name;
215 }
216 }
217 }
218 }
219
220 // Dependent fields are required when the target field is present (not blank).
221 // Todo: Support dependent and target fields that are radio button groups, or select drop-down lists.
222 // Todo: Make the dependency based on a specific value of the target field.
223 // Todo: allow dependent fields to have several required values, like {checkboxgroup: 3}.
224 if(lang.isObject(profile.dependencies)){
225 // properties of dependencies object are the names of dependent fields to be checked
226 for(name in profile.dependencies){
227 var elem = form[name]; // the dependent element
228 if(_undef("type", elem)){continue;}
229 if(elem.type != "text" && elem.type != "textarea" && elem.type != "password"){ continue; } // limited support
230 if(/\S+/.test(elem.value)){ continue; } // has a value already
231 if(results.isMissing(elem.name)){ continue; } // already listed as missing
232 var target = form[profile.dependencies[name]];
233 if(target.type != "text" && target.type != "textarea" && target.type != "password"){ continue; } // limited support
234 if(/^\s*$/.test(target.value)){ continue; } // skip if blank
235 missing[missing.length] = elem.name; // ok the dependent field is missing
236 }
237 }
238
239 // Find invalid input fields.
240 if(lang.isObject(profile.constraints)){
241 // constraint properties are the names of fields to be validated
242 for(name in profile.constraints){
243 var elem = form[name];
244 if(!elem) {continue;}
245
246 // skip if blank - its optional unless required, in which case it
247 // is already listed as missing.
248 if(!_undef("tagName",elem)
249 && (elem.tagName.toLowerCase().indexOf("input") >= 0
250 || elem.tagName.toLowerCase().indexOf("textarea") >= 0)
251 && /^\s*$/.test(elem.value)){
252 continue;
253 }
254
255 // constraintResponse should have two properties: isValid(bool), message(string)
256 var constraintResponse;
257 // case 1: constraint value is validation function
258 if(lang.isFunction(profile.constraints[name])){
259 constraintResponse = profile.constraints[name](elem.value);
260 }else if(lang.isFunction(lang.getObject(name, false, profile.constraints))){
261 // case 2: constraint value is validation function name as string
262 constraintResponse = lang.getObject(name, false, profile.constraints)(elem.value);
263 }else if(lang.isArray(profile.constraints[name])){
264
265 // handle nested arrays for multiple constraints
266 if(lang.isArray(profile.constraints[name][0])){
267 for(var i=0; i<profile.constraints[name].length; i++){
268 constraintResponse = validate.evaluateConstraint(profile, profile.constraints[name][i], name, elem);
269 if(!constraintResponse.isValid){ break; }
270 }
271 }else{
272 // case 3: constraint value is array, first elem is function,
273 // tail is parameters
274 if(lang.isFunction(lang.getObject(name, false, profile.constraints))){
275 constraintResponse = validate.evaluateConstraint(profile, profile.constraints[profile.constraints[name]], name, elem);
276 }else{
277 constraintResponse = validate.evaluateConstraint(profile, profile.constraints[name], name, elem);
278 }
279 }
280 }
281
282 // if constraintResponse is false (backwards compatibility with last version) or if property isValid is false, return the invalid field name and/or the constraintResponse message
283 if(!constraintResponse){
284 invalid[invalid.length] = elem.name;
285 }else if(typeof constraintResponse !== "boolean" && !constraintResponse.isValid){
286 invalid[invalid.length] = { field : elem.name, message : constraintResponse.message };
287 }
288 }
289 }
290
291 // Find unequal confirm fields and report them as Invalid.
292 if(lang.isObject(profile.confirm)){
293 for(name in profile.confirm){
294 var elem = form[name]; // the confirm element
295 var target = form[profile.confirm[name]];
296 if (_undef("type", elem) || _undef("type", target) || (elem.type != "text" && elem.type != "textarea" && elem.type != "password")
297 ||(target.type != elem.type)
298 ||(target.value == elem.value) // it's valid
299 ||(results.isInvalid(elem.name))// already listed as invalid
300 ||(/^\s*$/.test(target.value))) // skip if blank - only confirm if target has a value
301 {
302 continue;
303 }
304 invalid[invalid.length] = elem.name;
305 }
306 }
307 return results; // Object
308 };
309
310 //TODO: evaluateConstraint doesn't use profile or fieldName args?
311 validate.evaluateConstraint=function(profile, /*Array*/constraint, fieldName, elem){
312 // summary:
313 // Evaluates dojo.validate.check() constraints that are specified as array
314 // arguments
315 // description:
316 // The arrays are expected to be in the format of:
317 // | constraints:{
318 // | fieldName: [functionToCall, param1, param2, etc.],
319 // | fieldName: [[functionToCallFirst, param1],[functionToCallSecond,param2]]
320 // | }
321 //
322 // This function evaluates a single array function in the format of:
323 // [functionName, argument1, argument2, etc]
324 //
325 // The function will be parsed out and evaluated against the incoming parameters.
326 // profile:
327 // The dojo.validate.check() profile that this evaluation is against.
328 // constraint:
329 // The single [] array of function and arguments for the function.
330 // fieldName:
331 // The form dom name of the field being validated.
332 // elem:
333 // The form element field.
334
335 var isValidSomething = constraint[0];
336 var params = constraint.slice(1);
337 params.unshift(elem.value);
338 if(typeof isValidSomething != "undefined" && typeof isValidSomething != "string"){
339 return isValidSomething.apply(null, params);
340 }else if(typeof isValidSomething != "undefined" && typeof isValidSomething == "string"){
341 if(lang.isFunction(lang.getObject(isValidSomething))){
342 return lang.getObject(isValidSomething).apply(null, params);
343 }
344 }
345 return false; // Boolean
346 };
347
348 return validate.check;
349 });