check.js 12 KB

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