3 * Copyright(c) 2006-2010 Ext JS, Inc.
5 * http://www.extjs.com/license
8 * @class Ext.form.TextField
9 * @extends Ext.form.Field
10 * <p>Basic text field. Can be used as a direct replacement for traditional text inputs,
11 * or as the base class for more sophisticated input controls (like {@link Ext.form.TextArea}
12 * and {@link Ext.form.ComboBox}).</p>
13 * <p><b><u>Validation</u></b></p>
14 * <p>The validation procedure is described in the documentation for {@link #validateValue}.</p>
15 * <p><b><u>Alter Validation Behavior</u></b></p>
16 * <p>Validation behavior for each field can be configured:</p>
17 * <div class="mdetail-params"><ul>
18 * <li><code>{@link Ext.form.TextField#invalidText invalidText}</code> : the default validation message to
19 * show if any validation step above does not provide a message when invalid</li>
20 * <li><code>{@link Ext.form.TextField#maskRe maskRe}</code> : filter out keystrokes before any validation occurs</li>
21 * <li><code>{@link Ext.form.TextField#stripCharsRe stripCharsRe}</code> : filter characters after being typed in,
22 * but before being validated</li>
23 * <li><code>{@link Ext.form.Field#invalidClass invalidClass}</code> : alternate style when invalid</li>
24 * <li><code>{@link Ext.form.Field#validateOnBlur validateOnBlur}</code>,
25 * <code>{@link Ext.form.Field#validationDelay validationDelay}</code>, and
26 * <code>{@link Ext.form.Field#validationEvent validationEvent}</code> : modify how/when validation is triggered</li>
29 * @constructor Creates a new TextField
30 * @param {Object} config Configuration options
34 Ext.form.TextField = Ext.extend(Ext.form.Field, {
36 * @cfg {String} vtypeText A custom error message to display in place of the default message provided
37 * for the <b><code>{@link #vtype}</code></b> currently set for this field (defaults to <tt>''</tt>). <b>Note</b>:
38 * only applies if <b><code>{@link #vtype}</code></b> is set, else ignored.
41 * @cfg {RegExp} stripCharsRe A JavaScript RegExp object used to strip unwanted content from the value
42 * before validation (defaults to <tt>null</tt>).
45 * @cfg {Boolean} grow <tt>true</tt> if this field should automatically grow and shrink to its content
46 * (defaults to <tt>false</tt>)
50 * @cfg {Number} growMin The minimum width to allow when <code><b>{@link #grow}</b> = true</code> (defaults
55 * @cfg {Number} growMax The maximum width to allow when <code><b>{@link #grow}</b> = true</code> (defaults
60 * @cfg {String} vtype A validation type name as defined in {@link Ext.form.VTypes} (defaults to <tt>null</tt>)
64 * @cfg {RegExp} maskRe An input mask regular expression that will be used to filter keystrokes that do
65 * not match (defaults to <tt>null</tt>)
69 * @cfg {Boolean} disableKeyFilter Specify <tt>true</tt> to disable input keystroke filtering (defaults
72 disableKeyFilter : false,
74 * @cfg {Boolean} allowBlank Specify <tt>false</tt> to validate that the value's length is > 0 (defaults to
79 * @cfg {Number} minLength Minimum input field length required (defaults to <tt>0</tt>)
83 * @cfg {Number} maxLength Maximum input field length allowed by validation (defaults to Number.MAX_VALUE).
84 * This behavior is intended to provide instant feedback to the user by improving usability to allow pasting
85 * and editing or overtyping and back tracking. To restrict the maximum number of characters that can be
86 * entered into the field use <tt><b>{@link Ext.form.Field#autoCreate autoCreate}</b></tt> to add
87 * any attributes you want to a field, for example:<pre><code>
88 var myField = new Ext.form.NumberField({
92 maxLength: 16, // for validation
93 autoCreate: {tag: 'input', type: 'text', size: '20', autocomplete: 'off', maxlength: '10'}
97 maxLength : Number.MAX_VALUE,
99 * @cfg {String} minLengthText Error text to display if the <b><tt>{@link #minLength minimum length}</tt></b>
100 * validation fails (defaults to <tt>'The minimum length for this field is {minLength}'</tt>)
102 minLengthText : 'The minimum length for this field is {0}',
104 * @cfg {String} maxLengthText Error text to display if the <b><tt>{@link #maxLength maximum length}</tt></b>
105 * validation fails (defaults to <tt>'The maximum length for this field is {maxLength}'</tt>)
107 maxLengthText : 'The maximum length for this field is {0}',
109 * @cfg {Boolean} selectOnFocus <tt>true</tt> to automatically select any existing field text when the field
110 * receives input focus (defaults to <tt>false</tt>)
112 selectOnFocus : false,
114 * @cfg {String} blankText The error text to display if the <b><tt>{@link #allowBlank}</tt></b> validation
115 * fails (defaults to <tt>'This field is required'</tt>)
117 blankText : 'This field is required',
119 * @cfg {Function} validator
120 * <p>A custom validation function to be called during field validation ({@link #validateValue})
121 * (defaults to <tt>null</tt>). If specified, this function will be called first, allowing the
122 * developer to override the default validation process.</p>
123 * <br><p>This function will be passed the following Parameters:</p>
124 * <div class="mdetail-params"><ul>
125 * <li><code>value</code>: <i>Mixed</i>
126 * <div class="sub-desc">The current field value</div></li>
128 * <br><p>This function is to Return:</p>
129 * <div class="mdetail-params"><ul>
130 * <li><code>true</code>: <i>Boolean</i>
131 * <div class="sub-desc"><code>true</code> if the value is valid</div></li>
132 * <li><code>msg</code>: <i>String</i>
133 * <div class="sub-desc">An error message if the value is invalid</div></li>
138 * @cfg {RegExp} regex A JavaScript RegExp object to be tested against the field value during validation
139 * (defaults to <tt>null</tt>). If the test fails, the field will be marked invalid using
140 * <b><tt>{@link #regexText}</tt></b>.
144 * @cfg {String} regexText The error text to display if <b><tt>{@link #regex}</tt></b> is used and the
145 * test fails during validation (defaults to <tt>''</tt>)
149 * @cfg {String} emptyText The default text to place into an empty field (defaults to <tt>null</tt>).
150 * <b>Note</b>: that this value will be submitted to the server if this field is enabled and configured
151 * with a {@link #name}.
155 * @cfg {String} emptyClass The CSS class to apply to an empty field to style the <b><tt>{@link #emptyText}</tt></b>
156 * (defaults to <tt>'x-form-empty-field'</tt>). This class is automatically added and removed as needed
157 * depending on the current field value.
159 emptyClass : 'x-form-empty-field',
162 * @cfg {Boolean} enableKeyEvents <tt>true</tt> to enable the proxying of key events for the HTML input
163 * field (defaults to <tt>false</tt>)
166 initComponent : function(){
167 Ext.form.TextField.superclass.initComponent.call(this);
171 * Fires when the <tt><b>{@link #autoSize}</b></tt> function is triggered. The field may or
172 * may not have actually changed size according to the default logic, but this event provides
173 * a hook for the developer to apply additional logic at runtime to resize the field if needed.
174 * @param {Ext.form.Field} this This text field
175 * @param {Number} width The new field width
181 * Keydown input field event. This event only fires if <tt><b>{@link #enableKeyEvents}</b></tt>
183 * @param {Ext.form.TextField} this This text field
184 * @param {Ext.EventObject} e
189 * Keyup input field event. This event only fires if <tt><b>{@link #enableKeyEvents}</b></tt>
191 * @param {Ext.form.TextField} this This text field
192 * @param {Ext.EventObject} e
197 * Keypress input field event. This event only fires if <tt><b>{@link #enableKeyEvents}</b></tt>
199 * @param {Ext.form.TextField} this This text field
200 * @param {Ext.EventObject} e
207 initEvents : function(){
208 Ext.form.TextField.superclass.initEvents.call(this);
209 if(this.validationEvent == 'keyup'){
210 this.validationTask = new Ext.util.DelayedTask(this.validate, this);
211 this.mon(this.el, 'keyup', this.filterValidation, this);
213 else if(this.validationEvent !== false && this.validationEvent != 'blur'){
214 this.mon(this.el, this.validationEvent, this.validate, this, {buffer: this.validationDelay});
216 if(this.selectOnFocus || this.emptyText){
217 this.mon(this.el, 'mousedown', this.onMouseDown, this);
220 this.applyEmptyText();
223 if(this.maskRe || (this.vtype && this.disableKeyFilter !== true && (this.maskRe = Ext.form.VTypes[this.vtype+'Mask']))){
224 this.mon(this.el, 'keypress', this.filterKeys, this);
227 this.mon(this.el, 'keyup', this.onKeyUpBuffered, this, {buffer: 50});
228 this.mon(this.el, 'click', this.autoSize, this);
230 if(this.enableKeyEvents){
234 keydown: this.onKeyDown,
235 keypress: this.onKeyPress
240 onMouseDown: function(e){
242 this.mon(this.el, 'mouseup', Ext.emptyFn, this, { single: true, preventDefault: true });
246 processValue : function(value){
247 if(this.stripCharsRe){
248 var newValue = value.replace(this.stripCharsRe, '');
249 if(newValue !== value){
250 this.setRawValue(newValue);
257 filterValidation : function(e){
258 if(!e.isNavKeyPress()){
259 this.validationTask.delay(this.validationDelay);
264 onDisable: function(){
265 Ext.form.TextField.superclass.onDisable.call(this);
267 this.el.dom.unselectable = 'on';
272 onEnable: function(){
273 Ext.form.TextField.superclass.onEnable.call(this);
275 this.el.dom.unselectable = '';
280 onKeyUpBuffered : function(e){
281 if(this.doAutoSize(e)){
287 doAutoSize : function(e){
288 return !e.isNavKeyPress();
292 onKeyUp : function(e){
293 this.fireEvent('keyup', this, e);
297 onKeyDown : function(e){
298 this.fireEvent('keydown', this, e);
302 onKeyPress : function(e){
303 this.fireEvent('keypress', this, e);
307 * Resets the current field value to the originally-loaded value and clears any validation messages.
308 * Also adds <tt><b>{@link #emptyText}</b></tt> and <tt><b>{@link #emptyClass}</b></tt> if the
309 * original value was blank.
312 Ext.form.TextField.superclass.reset.call(this);
313 this.applyEmptyText();
316 applyEmptyText : function(){
317 if(this.rendered && this.emptyText && this.getRawValue().length < 1 && !this.hasFocus){
318 this.setRawValue(this.emptyText);
319 this.el.addClass(this.emptyClass);
324 preFocus : function(){
327 if(el.dom.value == this.emptyText){
328 this.setRawValue('');
330 el.removeClass(this.emptyClass);
332 if(this.selectOnFocus){
338 postBlur : function(){
339 this.applyEmptyText();
343 filterKeys : function(e){
348 if(Ext.isGecko && (e.isNavKeyPress() || k == e.BACKSPACE || (k == e.DELETE && e.button == -1))){
351 var cc = String.fromCharCode(e.getCharCode());
352 if(!Ext.isGecko && e.isSpecialKey() && !cc){
355 if(!this.maskRe.test(cc)){
360 setValue : function(v){
361 if(this.emptyText && this.el && !Ext.isEmpty(v)){
362 this.el.removeClass(this.emptyClass);
364 Ext.form.TextField.superclass.setValue.apply(this, arguments);
365 this.applyEmptyText();
371 * <p>Validates a value according to the field's validation rules and returns an array of errors
372 * for any failing validations. Validation rules are processed in the following order:</p>
373 * <div class="mdetail-params"><ul>
375 * <li><b>1. Field specific validator</b>
376 * <div class="sub-desc">
377 * <p>A validator offers a way to customize and reuse a validation specification.
378 * If a field is configured with a <code>{@link #validator}</code>
379 * function, it will be passed the current field value. The <code>{@link #validator}</code>
380 * function is expected to return either:
381 * <div class="mdetail-params"><ul>
382 * <li>Boolean <tt>true</tt> if the value is valid (validation continues).</li>
383 * <li>a String to represent the invalid message if invalid (validation halts).</li>
387 * <li><b>2. Basic Validation</b>
388 * <div class="sub-desc">
389 * <p>If the <code>{@link #validator}</code> has not halted validation,
390 * basic validation proceeds as follows:</p>
392 * <div class="mdetail-params"><ul>
394 * <li><code>{@link #allowBlank}</code> : (Invalid message =
395 * <code>{@link #emptyText}</code>)<div class="sub-desc">
396 * Depending on the configuration of <code>{@link #allowBlank}</code>, a
397 * blank field will cause validation to halt at this step and return
398 * Boolean true or false accordingly.
401 * <li><code>{@link #minLength}</code> : (Invalid message =
402 * <code>{@link #minLengthText}</code>)<div class="sub-desc">
403 * If the passed value does not satisfy the <code>{@link #minLength}</code>
404 * specified, validation halts.
407 * <li><code>{@link #maxLength}</code> : (Invalid message =
408 * <code>{@link #maxLengthText}</code>)<div class="sub-desc">
409 * If the passed value does not satisfy the <code>{@link #maxLength}</code>
410 * specified, validation halts.
416 * <li><b>3. Preconfigured Validation Types (VTypes)</b>
417 * <div class="sub-desc">
418 * <p>If none of the prior validation steps halts validation, a field
419 * configured with a <code>{@link #vtype}</code> will utilize the
420 * corresponding {@link Ext.form.VTypes VTypes} validation function.
421 * If invalid, either the field's <code>{@link #vtypeText}</code> or
422 * the VTypes vtype Text property will be used for the invalid message.
423 * Keystrokes on the field will be filtered according to the VTypes
424 * vtype Mask property.</p>
427 * <li><b>4. Field specific regex test</b>
428 * <div class="sub-desc">
429 * <p>If none of the prior validation steps halts validation, a field's
430 * configured <code>{@link #regex}</code> test will be processed.
431 * The invalid message for this test is configured with
432 * <code>{@link #regexText}</code>.</p>
435 * @param {Mixed} value The value to validate. The processed raw value will be used if nothing is passed
436 * @return {Array} Array of any validation errors
438 getErrors: function(value) {
439 var errors = Ext.form.TextField.superclass.getErrors.apply(this, arguments);
441 value = value || this.processValue(this.getRawValue());
443 if (Ext.isFunction(this.validator)) {
444 var msg = this.validator(value);
450 if (value.length < 1 || value === this.emptyText) {
451 if (this.allowBlank) {
452 //if value is blank and allowBlank is true, there cannot be any additional errors
455 errors.push(this.blankText);
459 if (!this.allowBlank && (value.length < 1 || value === this.emptyText)) { // if it's blank
460 errors.push(this.blankText);
463 if (value.length < this.minLength) {
464 errors.push(String.format(this.minLengthText, this.minLength));
467 if (value.length > this.maxLength) {
468 errors.push(String.format(this.maxLengthText, this.maxLength));
472 var vt = Ext.form.VTypes;
473 if(!vt[this.vtype](value, this)){
474 errors.push(this.vtypeText || vt[this.vtype +'Text']);
478 if (this.regex && !this.regex.test(value)) {
479 errors.push(this.regexText);
486 * Selects text in this field
487 * @param {Number} start (optional) The index where the selection should start (defaults to 0)
488 * @param {Number} end (optional) The index where the selection should end (defaults to the text length)
490 selectText : function(start, end){
491 var v = this.getRawValue();
494 start = start === undefined ? 0 : start;
495 end = end === undefined ? v.length : end;
497 if(d.setSelectionRange){
498 d.setSelectionRange(start, end);
499 }else if(d.createTextRange){
500 var range = d.createTextRange();
501 range.moveStart('character', start);
502 range.moveEnd('character', end-v.length);
505 doFocus = Ext.isGecko || Ext.isOpera;
515 * Automatically grows the field to accomodate the width of the text up to the maximum field width allowed.
516 * This only takes effect if <tt><b>{@link #grow}</b> = true</tt>, and fires the {@link #autosize} event.
518 autoSize : function(){
519 if(!this.grow || !this.rendered){
523 this.metrics = Ext.util.TextMetrics.createInstance(this.el);
526 var v = el.dom.value;
527 var d = document.createElement('div');
528 d.appendChild(document.createTextNode(v));
533 var w = Math.min(this.growMax, Math.max(this.metrics.getWidth(v) + /* add extra padding */ 10, this.growMin));
535 this.fireEvent('autosize', this, w);
538 onDestroy: function(){
539 if(this.validationTask){
540 this.validationTask.cancel();
541 this.validationTask = null;
543 Ext.form.TextField.superclass.onDestroy.call(this);
546 Ext.reg('textfield', Ext.form.TextField);