Debian Codegraph @

dijit/form/ValidationTextBox.js

raw symbols SCIP
1 define([
2 "dojo/_base/declare", // declare
3 "dojo/_base/kernel", // kernel.deprecated
4 "dojo/_base/lang",
5 "dojo/i18n", // i18n.getLocalization
6 "./TextBox",
7 "../Tooltip",
8 "dojo/text!./templates/ValidationTextBox.html",
9 "dojo/i18n!./nls/validate"
10 ], function(declare, kernel, lang, i18n, TextBox, Tooltip, template){
11
12 // module:
13 // dijit/form/ValidationTextBox
14
15
16 var ValidationTextBox = declare("dijit.form.ValidationTextBox", TextBox, {
17 // summary:
18 // Base class for textbox widgets with the ability to validate content of various types and provide user feedback.
19
20 templateString: template,
21
22 // required: Boolean
23 // User is required to enter data into this field.
24 required: false,
25
26 // promptMessage: String
27 // If defined, display this hint string immediately on focus to the textbox, if empty.
28 // Also displays if the textbox value is Incomplete (not yet valid but will be with additional input).
29 // Think of this like a tooltip that tells the user what to do, not an error message
30 // that tells the user what they've done wrong.
31 //
32 // Message disappears when user starts typing.
33 promptMessage: "",
34
35 // invalidMessage: String
36 // The message to display if value is invalid.
37 // The translated string value is read from the message file by default.
38 // Set to "" to use the promptMessage instead.
39 invalidMessage: "$_unset_$",
40
41 // missingMessage: String
42 // The message to display if value is empty and the field is required.
43 // The translated string value is read from the message file by default.
44 // Set to "" to use the invalidMessage instead.
45 missingMessage: "$_unset_$",
46
47 // message: String
48 // Currently error/prompt message.
49 // When using the default tooltip implementation, this will only be
50 // displayed when the field is focused.
51 message: "",
52
53 // constraints: ValidationTextBox.__Constraints
54 // Despite the name, this parameter specifies both constraints on the input as well as
55 // formatting options. See `dijit/form/ValidationTextBox.__Constraints` for details.
56 constraints:{},
57
58 // pattern: [extension protected] String|Function(constraints) returning a string.
59 // This defines the regular expression used to validate the input.
60 // Do not add leading ^ or $ characters since the widget adds these.
61 // A function may be used to generate a valid pattern when dependent on constraints or other runtime factors.
62 // set('pattern', String|Function).
63 pattern: ".*",
64
65 // regExp: Deprecated [extension protected] String. Use "pattern" instead.
66 regExp: "",
67
68 regExpGen: function(/*__Constraints*/ /*===== constraints =====*/){
69 // summary:
70 // Deprecated. Use set('pattern', Function) instead.
71 },
72
73 // state: [readonly] String
74 // Shows current state (ie, validation result) of input (""=Normal, Incomplete, or Error)
75 state: "",
76
77 // tooltipPosition: String[]
78 // See description of `dijit/Tooltip.defaultPosition` for details on this parameter.
79 tooltipPosition: [],
80
81 _deprecateRegExp: function(attr, value){
82 if(value != ValidationTextBox.prototype[attr]){
83 kernel.deprecated("ValidationTextBox id="+this.id+", set('" + attr + "', ...) is deprecated. Use set('pattern', ...) instead.", "", "2.0");
84 this.set('pattern', value);
85 }
86 },
87 _setRegExpGenAttr: function(/*Function*/ newFcn){
88 this._deprecateRegExp("regExpGen", newFcn);
89 this._set("regExpGen", this._computeRegexp); // backward compat with this.regExpGen(this.constraints)
90 },
91 _setRegExpAttr: function(/*String*/ value){
92 this._deprecateRegExp("regExp", value);
93 },
94
95 _setValueAttr: function(){
96 // summary:
97 // Hook so set('value', ...) works.
98 this.inherited(arguments);
99 this._refreshState();
100 },
101
102 validator: function(/*anything*/ value, /*__Constraints*/ constraints){
103 // summary:
104 // Overridable function used to validate the text input against the regular expression.
105 // tags:
106 // protected
107 return (new RegExp("^(?:" + this._computeRegexp(constraints) + ")"+(this.required?"":"?")+"$")).test(value) &&
108 (!this.required || !this._isEmpty(value)) &&
109 (this._isEmpty(value) || this.parse(value, constraints) !== undefined); // Boolean
110 },
111
112 _isValidSubset: function(){
113 // summary:
114 // Returns true if the value is either already valid or could be made valid by appending characters.
115 // This is used for validation while the user [may be] still typing.
116 return this.textbox.value.search(this._partialre) == 0;
117 },
118
119 isValid: function(/*Boolean*/ /*===== isFocused =====*/){
120 // summary:
121 // Tests if value is valid.
122 // Can override with your own routine in a subclass.
123 // tags:
124 // protected
125 return this.validator(this.textbox.value, this.get('constraints'));
126 },
127
128 _isEmpty: function(value){
129 // summary:
130 // Checks for whitespace
131 return (this.trim ? /^\s*$/ : /^$/).test(value); // Boolean
132 },
133
134 getErrorMessage: function(/*Boolean*/ /*===== isFocused =====*/){
135 // summary:
136 // Return an error message to show if appropriate
137 // tags:
138 // protected
139 var invalid = this.invalidMessage == "$_unset_$" ? this.messages.invalidMessage :
140 !this.invalidMessage ? this.promptMessage : this.invalidMessage;
141 var missing = this.missingMessage == "$_unset_$" ? this.messages.missingMessage :
142 !this.missingMessage ? invalid : this.missingMessage;
143 return (this.required && this._isEmpty(this.textbox.value)) ? missing : invalid; // String
144 },
145
146 getPromptMessage: function(/*Boolean*/ /*===== isFocused =====*/){
147 // summary:
148 // Return a hint message to show when widget is first focused
149 // tags:
150 // protected
151 return this.promptMessage; // String
152 },
153
154 _maskValidSubsetError: true,
155 validate: function(/*Boolean*/ isFocused){
156 // summary:
157 // Called by oninit, onblur, and onkeypress.
158 // description:
159 // Show missing or invalid messages if appropriate, and highlight textbox field.
160 // tags:
161 // protected
162 var message = "";
163 var isValid = this.disabled || this.isValid(isFocused);
164 if(isValid){ this._maskValidSubsetError = true; }
165 var isEmpty = this._isEmpty(this.textbox.value);
166 var isValidSubset = !isValid && isFocused && this._isValidSubset();
167 this._set("state", isValid ? "" : (((((!this._hasBeenBlurred || isFocused) && isEmpty) || isValidSubset) && (this._maskValidSubsetError || (isValidSubset && !this._hasBeenBlurred && isFocused))) ? "Incomplete" : "Error"));
168 this.focusNode.setAttribute("aria-invalid", this.state == "Error" ? "true" : "false");
169
170 if(this.state == "Error"){
171 this._maskValidSubsetError = isFocused && isValidSubset; // we want the error to show up after a blur and refocus
172 message = this.getErrorMessage(isFocused);
173 }else if(this.state == "Incomplete"){
174 message = this.getPromptMessage(isFocused); // show the prompt whenever the value is not yet complete
175 this._maskValidSubsetError = !this._hasBeenBlurred || isFocused; // no Incomplete warnings while focused
176 }else if(isEmpty){
177 message = this.getPromptMessage(isFocused); // show the prompt whenever there's no error and no text
178 }
179 this.set("message", message);
180
181 return isValid;
182 },
183
184 displayMessage: function(/*String*/ message){
185 // summary:
186 // Overridable method to display validation errors/hints.
187 // By default uses a tooltip.
188 // tags:
189 // extension
190 if(message && this.focused){
191 Tooltip.show(message, this.domNode, this.tooltipPosition, !this.isLeftToRight());
192 }else{
193 Tooltip.hide(this.domNode);
194 }
195 },
196
197 _refreshState: function(){
198 // Overrides TextBox._refreshState()
199 if(this._created){ // should instead be this._started but that would require all programmatic ValidationTextBox instantiations to call startup()
200 this.validate(this.focused);
201 }
202 this.inherited(arguments);
203 },
204
205 //////////// INITIALIZATION METHODS ///////////////////////////////////////
206
207 constructor: function(params /*===== , srcNodeRef =====*/){
208 // summary:
209 // Create the widget.
210 // params: Object|null
211 // Hash of initialization parameters for widget, including scalar values (like title, duration etc.)
212 // and functions, typically callbacks like onClick.
213 // The hash can contain any of the widget's properties, excluding read-only properties.
214 // srcNodeRef: DOMNode|String?
215 // If a srcNodeRef (DOM node) is specified, replace srcNodeRef with my generated DOM tree.
216
217 this.constraints = lang.clone(this.constraints);
218 this.baseClass += ' dijitValidationTextBox';
219 },
220
221 startup: function(){
222 this.inherited(arguments);
223 this._refreshState(); // after all _set* methods have run
224 },
225
226 _setConstraintsAttr: function(/*__Constraints*/ constraints){
227 if(!constraints.locale && this.lang){
228 constraints.locale = this.lang;
229 }
230 this._set("constraints", constraints);
231 this._refreshState();
232 },
233
234 _setPatternAttr: function(/*String|Function*/ pattern){
235 this._set("pattern", pattern); // don't set on INPUT to avoid native HTML5 validation
236 this._refreshState();
237 },
238
239 _computeRegexp: function(/*__Constraints*/ constraints){
240 // summary:
241 // Hook to get the current regExp and to compute the partial validation RE.
242
243 var p = this.pattern;
244 if(typeof p == "function"){
245 p = p.call(this, constraints);
246 }
247 if(p != this._lastRegExp){
248 var partialre = "";
249 this._lastRegExp = p;
250 // parse the regexp and produce a new regexp that matches valid subsets
251 // if the regexp is .* then there's no use in matching subsets since everything is valid
252 if(p != ".*"){
253 p.replace(/\\.|\[\]|\[.*?[^\\]{1}\]|\{.*?\}|\(\?[=:!]|./g,
254 function(re){
255 switch(re.charAt(0)){
256 case '{':
257 case '+':
258 case '?':
259 case '*':
260 case '^':
261 case '$':
262 case '|':
263 case '(':
264 partialre += re;
265 break;
266 case ")":
267 partialre += "|$)";
268 break;
269 default:
270 partialre += "(?:"+re+"|$)";
271 break;
272 }
273 });
274 }
275 try{ // this is needed for now since the above regexp parsing needs more test verification
276 "".search(partialre);
277 }catch(e){ // should never be here unless the original RE is bad or the parsing is bad
278 partialre = this.pattern;
279 console.warn('RegExp error in ' + this.declaredClass + ': ' + this.pattern);
280 } // should never be here unless the original RE is bad or the parsing is bad
281 this._partialre = "^(?:" + partialre + ")$";
282 }
283 return p;
284 },
285
286 postMixInProperties: function(){
287 this.inherited(arguments);
288 this.messages = i18n.getLocalization("dijit.form", "validate", this.lang);
289 this._setConstraintsAttr(this.constraints); // this needs to happen now (and later) due to codependency on _set*Attr calls attachPoints
290 },
291
292 _setDisabledAttr: function(/*Boolean*/ value){
293 this.inherited(arguments); // call FormValueWidget._setDisabledAttr()
294 this._refreshState();
295 },
296
297 _setRequiredAttr: function(/*Boolean*/ value){
298 this._set("required", value);
299 this.focusNode.setAttribute("aria-required", value);
300 this._refreshState();
301 },
302
303 _setMessageAttr: function(/*String*/ message){
304 this._set("message", message);
305 this.displayMessage(message);
306 },
307
308 reset:function(){
309 // Overrides dijit/form/TextBox.reset() by also
310 // hiding errors about partial matches
311 this._maskValidSubsetError = true;
312 this.inherited(arguments);
313 },
314
315 _onBlur: function(){
316 // the message still exists but for back-compat, and to erase the tooltip
317 // (if the message is being displayed as a tooltip), call displayMessage('')
318 this.displayMessage('');
319
320 this.inherited(arguments);
321 },
322
323 destroy: function(){
324 Tooltip.hide(this.domNode); // in case tooltip show when ValidationTextBox (or enclosing Dialog) destroyed
325 this.inherited(arguments);
326 }
327 });
328
329 /*=====
330 ValidationTextBox.__Constraints = {
331 // locale: String
332 // locale used for validation, picks up value from this widget's lang attribute
333 // _flags_: anything
334 // various flags passed to pattern function
335 };
336 =====*/
337
338 return ValidationTextBox;
339 });