4 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
5 <title>The source code</title>
6 <link href="../prettify/prettify.css" type="text/css" rel="stylesheet" />
7 <script type="text/javascript" src="../prettify/prettify.js"></script>
8 <style type="text/css">
9 .highlight { display: block; background-color: #ddd; }
11 <script type="text/javascript">
12 function highlight() {
13 document.getElementById(location.hash.replace(/#/, "")).className = "highlight";
17 <body onload="prettyPrint(); highlight();">
18 <pre class="prettyprint lang-js"><span id='Ext-form-field-Text'>/**
19 </span> * @class Ext.form.field.Text
20 * @extends Ext.form.field.Base
22 A basic text field. Can be used as a direct replacement for traditional text inputs,
23 or as the base class for more sophisticated input controls (like {@link Ext.form.field.TextArea}
24 and {@link Ext.form.field.ComboBox}). Has support for empty-field placeholder values (see {@link #emptyText}).
28 The Text field has a useful set of validations built in:
30 - {@link #allowBlank} for making the field required
31 - {@link #minLength} for requiring a minimum value length
32 - {@link #maxLength} for setting a maximum value length (with {@link #enforceMaxLength} to add it
33 as the `maxlength` attribute on the input element)
34 - {@link #regex} to specify a custom regular expression for validation
36 In addition, custom validations may be added:
38 - {@link #vtype} specifies a virtual type implementation from {@link Ext.form.field.VTypes} which can contain
39 custom validation logic
40 - {@link #validator} allows a custom arbitrary function to be called during validation
42 The details around how and when each of these validation options get used are described in the
43 documentation for {@link #getErrors}.
45 By default, the field value is checked for validity immediately while the user is typing in the
46 field. This can be controlled with the {@link #validateOnChange}, {@link #checkChangeEvents}, and
47 {@link #checkChangeBugger} configurations. Also see the details on Form Validation in the
48 {@link Ext.form.Panel} class documentation.
50 #Masking and Character Stripping#
52 Text fields can be configured with custom regular expressions to be applied to entered values before
53 validation: see {@link #maskRe} and {@link #stripCharsRe} for details.
54 {@img Ext.form.Text/Ext.form.Text.png Ext.form.Text component}
57 Ext.create('Ext.form.Panel', {
58 title: 'Contact Info',
61 renderTo: Ext.getBody(),
66 allowBlank: false // requires a non-empty value
70 fieldLabel: 'Email Address',
71 vtype: 'email' // requires value to be a valid email address format
77 * @docauthor Jason Johnston <jason@sencha.com>
79 Ext.define('Ext.form.field.Text', {
80 extend:'Ext.form.field.Base',
81 alias: 'widget.textfield',
82 requires: ['Ext.form.field.VTypes', 'Ext.layout.component.field.Text'],
83 alternateClassName: ['Ext.form.TextField', 'Ext.form.Text'],
85 <span id='Ext-form-field-Text-cfg-vtypeText'> /**
86 </span> * @cfg {String} vtypeText A custom error message to display in place of the default message provided
87 * for the <b><code>{@link #vtype}</code></b> currently set for this field (defaults to <tt>undefined</tt>).
88 * <b>Note</b>: only applies if <b><code>{@link #vtype}</code></b> is set, else ignored.
91 <span id='Ext-form-field-Text-cfg-stripCharsRe'> /**
92 </span> * @cfg {RegExp} stripCharsRe A JavaScript RegExp object used to strip unwanted content from the value
93 * before validation (defaults to <tt>undefined</tt>).
96 <span id='Ext-form-field-Text-cfg-size'> /**
97 </span> * @cfg {Number} size An initial value for the 'size' attribute on the text input element. This is only
98 * used if the field has no configured {@link #width} and is not given a width by its container's layout.
99 * Defaults to <tt>20</tt>.
103 <span id='Ext-form-field-Text-cfg-grow'> /**
104 </span> * @cfg {Boolean} grow <tt>true</tt> if this field should automatically grow and shrink to its content
105 * (defaults to <tt>false</tt>)
108 <span id='Ext-form-field-Text-cfg-growMin'> /**
109 </span> * @cfg {Number} growMin The minimum width to allow when <code><b>{@link #grow}</b> = true</code> (defaults
110 * to <tt>30</tt>)
114 <span id='Ext-form-field-Text-cfg-growMax'> /**
115 </span> * @cfg {Number} growMax The maximum width to allow when <code><b>{@link #grow}</b> = true</code> (defaults
116 * to <tt>800</tt>)
120 <span id='Ext-form-field-Text-cfg-growAppend'> /**
121 </span> * @cfg {String} growAppend
122 * A string that will be appended to the field's current value for the purposes of calculating the target
123 * field size. Only used when the {@link #grow} config is <tt>true</tt>. Defaults to a single capital "W"
124 * (the widest character in common fonts) to leave enough space for the next typed character and avoid the
125 * field value shifting before the width is adjusted.
129 <span id='Ext-form-field-Text-cfg-vtype'> /**
130 </span> * @cfg {String} vtype A validation type name as defined in {@link Ext.form.field.VTypes} (defaults to <tt>undefined</tt>)
133 <span id='Ext-form-field-Text-cfg-maskRe'> /**
134 </span> * @cfg {RegExp} maskRe An input mask regular expression that will be used to filter keystrokes that do
135 * not match (defaults to <tt>undefined</tt>)
138 <span id='Ext-form-field-Text-cfg-disableKeyFilter'> /**
139 </span> * @cfg {Boolean} disableKeyFilter Specify <tt>true</tt> to disable input keystroke filtering (defaults
140 * to <tt>false</tt>)
143 <span id='Ext-form-field-Text-cfg-allowBlank'> /**
144 </span> * @cfg {Boolean} allowBlank Specify <tt>false</tt> to validate that the value's length is > 0 (defaults to
145 * <tt>true</tt>)
149 <span id='Ext-form-field-Text-cfg-minLength'> /**
150 </span> * @cfg {Number} minLength Minimum input field length required (defaults to <tt>0</tt>)
154 <span id='Ext-form-field-Text-cfg-maxLength'> /**
155 </span> * @cfg {Number} maxLength Maximum input field length allowed by validation (defaults to Number.MAX_VALUE).
156 * This behavior is intended to provide instant feedback to the user by improving usability to allow pasting
157 * and editing or overtyping and back tracking. To restrict the maximum number of characters that can be
158 * entered into the field use the <tt><b>{@link Ext.form.field.Text#enforceMaxLength enforceMaxLength}</b></tt> option.
160 maxLength : Number.MAX_VALUE,
162 <span id='Ext-form-field-Text-cfg-enforceMaxLength'> /**
163 </span> * @cfg {Boolean} enforceMaxLength True to set the maxLength property on the underlying input field. Defaults to <tt>false</tt>
166 <span id='Ext-form-field-Text-cfg-minLengthText'> /**
167 </span> * @cfg {String} minLengthText Error text to display if the <b><tt>{@link #minLength minimum length}</tt></b>
168 * validation fails (defaults to <tt>'The minimum length for this field is {minLength}'</tt>)
170 minLengthText : 'The minimum length for this field is {0}',
172 <span id='Ext-form-field-Text-cfg-maxLengthText'> /**
173 </span> * @cfg {String} maxLengthText Error text to display if the <b><tt>{@link #maxLength maximum length}</tt></b>
174 * validation fails (defaults to <tt>'The maximum length for this field is {maxLength}'</tt>)
176 maxLengthText : 'The maximum length for this field is {0}',
178 <span id='Ext-form-field-Text-cfg-selectOnFocus'> /**
179 </span> * @cfg {Boolean} selectOnFocus <tt>true</tt> to automatically select any existing field text when the field
180 * receives input focus (defaults to <tt>false</tt>)
183 <span id='Ext-form-field-Text-cfg-blankText'> /**
184 </span> * @cfg {String} blankText The error text to display if the <b><tt>{@link #allowBlank}</tt></b> validation
185 * fails (defaults to <tt>'This field is required'</tt>)
187 blankText : 'This field is required',
189 <span id='Ext-form-field-Text-cfg-validator'> /**
190 </span> * @cfg {Function} validator
191 * <p>A custom validation function to be called during field validation ({@link #getErrors})
192 * (defaults to <tt>undefined</tt>). If specified, this function will be called first, allowing the
193 * developer to override the default validation process.</p>
194 * <br><p>This function will be passed the following Parameters:</p>
195 * <div class="mdetail-params"><ul>
196 * <li><code>value</code>: <i>Mixed</i>
197 * <div class="sub-desc">The current field value</div></li>
198 * </ul></div>
199 * <br><p>This function is to Return:</p>
200 * <div class="mdetail-params"><ul>
201 * <li><code>true</code>: <i>Boolean</i>
202 * <div class="sub-desc"><code>true</code> if the value is valid</div></li>
203 * <li><code>msg</code>: <i>String</i>
204 * <div class="sub-desc">An error message if the value is invalid</div></li>
205 * </ul></div>
208 <span id='Ext-form-field-Text-cfg-regex'> /**
209 </span> * @cfg {RegExp} regex A JavaScript RegExp object to be tested against the field value during validation
210 * (defaults to <tt>undefined</tt>). If the test fails, the field will be marked invalid using
211 * <b><tt>{@link #regexText}</tt></b>.
214 <span id='Ext-form-field-Text-cfg-regexText'> /**
215 </span> * @cfg {String} regexText The error text to display if <b><tt>{@link #regex}</tt></b> is used and the
216 * test fails during validation (defaults to <tt>''</tt>)
220 <span id='Ext-form-field-Text-cfg-emptyText'> /**
221 </span> * @cfg {String} emptyText
222 * <p>The default text to place into an empty field (defaults to <tt>undefined</tt>).</p>
223 * <p>Note that normally this value will be submitted to the server if this field is enabled; to prevent this
224 * you can set the {@link Ext.form.action.Action#submitEmptyText submitEmptyText} option of
225 * {@link Ext.form.Basic#submit} to <tt>false</tt>.</p>
226 * <p>Also note that if you use <tt>{@link #inputType inputType}:'file'</tt>, {@link #emptyText} is not
227 * supported and should be avoided.</p>
230 <span id='Ext-form-field-Text-cfg-emptyCls'> /**
231 </span> * @cfg {String} emptyCls The CSS class to apply to an empty field to style the <b><tt>{@link #emptyText}</tt></b>
232 * (defaults to <tt>'x-form-empty-field'</tt>). This class is automatically added and removed as needed
233 * depending on the current field value.
235 emptyCls : Ext.baseCSSPrefix + 'form-empty-field',
239 <span id='Ext-form-field-Text-cfg-enableKeyEvents'> /**
240 </span> * @cfg {Boolean} enableKeyEvents <tt>true</tt> to enable the proxying of key events for the HTML input field (defaults to <tt>false</tt>)
243 componentLayout: 'textfield',
245 initComponent : function(){
248 <span id='Ext-form-field-Text-event-autosize'> /**
249 </span> * @event autosize
250 * Fires when the <tt><b>{@link #autoSize}</b></tt> function is triggered and the field is
251 * resized according to the {@link #grow}/{@link #growMin}/{@link #growMax} configs as a result.
252 * This event provides a hook for the developer to apply additional logic at runtime to resize the
254 * @param {Ext.form.field.Text} this This text field
255 * @param {Number} width The new field width
259 <span id='Ext-form-field-Text-event-keydown'> /**
260 </span> * @event keydown
261 * Keydown input field event. This event only fires if <tt><b>{@link #enableKeyEvents}</b></tt>
263 * @param {Ext.form.field.Text} this This text field
264 * @param {Ext.EventObject} e
267 <span id='Ext-form-field-Text-event-keyup'> /**
268 </span> * @event keyup
269 * Keyup input field event. This event only fires if <tt><b>{@link #enableKeyEvents}</b></tt>
271 * @param {Ext.form.field.Text} this This text field
272 * @param {Ext.EventObject} e
275 <span id='Ext-form-field-Text-event-keypress'> /**
276 </span> * @event keypress
277 * Keypress input field event. This event only fires if <tt><b>{@link #enableKeyEvents}</b></tt>
279 * @param {Ext.form.field.Text} this This text field
280 * @param {Ext.EventObject} e
287 initEvents : function(){
292 if(me.selectOnFocus || me.emptyText){
293 me.mon(el, 'mousedown', me.onMouseDown, me);
295 if(me.maskRe || (me.vtype && me.disableKeyFilter !== true && (me.maskRe = Ext.form.field.VTypes[me.vtype+'Mask']))){
296 me.mon(el, 'keypress', me.filterKeys, me);
299 if (me.enableKeyEvents) {
303 keydown: me.onKeyDown,
304 keypress: me.onKeyPress
309 <span id='Ext-form-field-Text-method-isEqual'> /**
310 </span> * @private override - treat undefined and null values as equal to an empty string value
312 isEqual: function(value1, value2) {
313 return String(Ext.value(value1, '')) === String(Ext.value(value2, ''));
316 <span id='Ext-form-field-Text-method-onChange'> /**
318 * If grow=true, invoke the autoSize method when the field's value is changed.
320 onChange: function() {
325 afterRender: function(){
327 if (me.enforceMaxLength) {
328 me.inputEl.dom.maxLength = me.maxLength;
335 onMouseDown: function(e){
338 me.mon(me.inputEl, 'mouseup', Ext.emptyFn, me, { single: true, preventDefault: true });
342 <span id='Ext-form-field-Text-method-processRawValue'> /**
343 </span> * Performs any necessary manipulation of a raw String value to prepare it for {@link #stringToValue conversion}
344 * and/or {@link #validate validation}. For text fields this applies the configured {@link #stripCharsRe} to the
346 * @param {String} value The unprocessed string value
347 * @return {String} The processed string value
349 processRawValue: function(value) {
351 stripRe = me.stripCharsRe,
355 newValue = value.replace(stripRe, '');
356 if (newValue !== value) {
357 me.setRawValue(newValue);
365 onDisable: function(){
368 this.inputEl.dom.unselectable = 'on';
373 onEnable: function(){
376 this.inputEl.dom.unselectable = '';
380 onKeyDown: function(e) {
381 this.fireEvent('keydown', this, e);
384 onKeyUp: function(e) {
385 this.fireEvent('keyup', this, e);
388 onKeyPress: function(e) {
389 this.fireEvent('keypress', this, e);
392 <span id='Ext-form-field-Text-method-reset'> /**
393 </span> * Resets the current field value to the originally-loaded value and clears any validation messages.
394 * Also adds <tt><b>{@link #emptyText}</b></tt> and <tt><b>{@link #emptyCls}</b></tt> if the
395 * original value was blank.
399 this.applyEmptyText();
402 applyEmptyText : function(){
404 emptyText = me.emptyText,
407 if (me.rendered && emptyText) {
408 isEmpty = me.getRawValue().length < 1 && !me.hasFocus;
410 if (Ext.supports.Placeholder) {
411 me.inputEl.dom.placeholder = emptyText;
412 } else if (isEmpty) {
413 me.setRawValue(emptyText);
416 //all browsers need this because of a styling issue with chrome + placeholders.
417 //the text isnt vertically aligned when empty (and using the placeholder)
419 me.inputEl.addCls(me.emptyCls);
427 preFocus : function(){
429 inputEl = me.inputEl,
430 emptyText = me.emptyText,
433 if (emptyText && !Ext.supports.Placeholder && inputEl.dom.value === emptyText) {
436 inputEl.removeCls(me.emptyCls);
437 } else if (Ext.supports.Placeholder) {
438 me.inputEl.removeCls(me.emptyCls);
440 if (me.selectOnFocus || isEmpty) {
441 inputEl.dom.select();
445 onFocus: function() {
447 me.callParent(arguments);
454 postBlur : function(){
455 this.applyEmptyText();
459 filterKeys : function(e){
463 var key = e.getKey(),
464 charCode = String.fromCharCode(e.getCharCode());
466 if(Ext.isGecko && (e.isNavKeyPress() || key === e.BACKSPACE || (key === e.DELETE && e.button === -1))){
470 if(!Ext.isGecko && e.isSpecialKey() && !charCode){
473 if(!this.maskRe.test(charCode)){
478 <span id='Ext-form-field-Text-method-getRawValue'> /**
479 </span> * Returns the raw String value of the field, without performing any normalization, conversion, or validation.
480 * Gets the current value of the input element if the field has been rendered, ignoring the value if it is the
481 * {@link #emptyText}. To get a normalized and converted value see {@link #getValue}.
482 * @return {String} value The raw String value of the field
484 getRawValue: function() {
487 if (v === me.emptyText) {
493 <span id='Ext-form-field-Text-method-setValue'> /**
494 </span> * Sets a data value into the field and runs the change detection and validation. Also applies any configured
495 * {@link #emptyText} for text fields. To set the value directly without these inspections see {@link #setRawValue}.
496 * @param {Mixed} value The value to set
497 * @return {Ext.form.field.Text} this
499 setValue: function(value) {
501 inputEl = me.inputEl;
503 if (inputEl && me.emptyText && !Ext.isEmpty(value)) {
504 inputEl.removeCls(me.emptyCls);
507 me.callParent(arguments);
513 <span id='Ext-form-field-Text-method-getErrors'> /**
514 </span>Validates a value according to the field's validation rules and returns an array of errors
515 for any failing validations. Validation rules are processed in the following order:
517 1. **Field specific validator**
519 A validator offers a way to customize and reuse a validation specification.
520 If a field is configured with a `{@link #validator}`
521 function, it will be passed the current field value. The `{@link #validator}`
522 function is expected to return either:
524 - Boolean `true` if the value is valid (validation continues).
525 - a String to represent the invalid message if invalid (validation halts).
527 2. **Basic Validation**
529 If the `{@link #validator}` has not halted validation,
530 basic validation proceeds as follows:
532 - `{@link #allowBlank}` : (Invalid message = `{@link #emptyText}`)
534 Depending on the configuration of <code>{@link #allowBlank}</code>, a
535 blank field will cause validation to halt at this step and return
536 Boolean true or false accordingly.
538 - `{@link #minLength}` : (Invalid message = `{@link #minLengthText}`)
540 If the passed value does not satisfy the `{@link #minLength}`
541 specified, validation halts.
543 - `{@link #maxLength}` : (Invalid message = `{@link #maxLengthText}`)
545 If the passed value does not satisfy the `{@link #maxLength}`
546 specified, validation halts.
548 3. **Preconfigured Validation Types (VTypes)**
550 If none of the prior validation steps halts validation, a field
551 configured with a `{@link #vtype}` will utilize the
552 corresponding {@link Ext.form.field.VTypes VTypes} validation function.
553 If invalid, either the field's `{@link #vtypeText}` or
554 the VTypes vtype Text property will be used for the invalid message.
555 Keystrokes on the field will be filtered according to the VTypes
558 4. **Field specific regex test**
560 If none of the prior validation steps halts validation, a field's
561 configured <code>{@link #regex}</code> test will be processed.
562 The invalid message for this test is configured with `{@link #regexText}`
564 * @param {Mixed} value The value to validate. The processed raw value will be used if nothing is passed
565 * @return {Array} Array of any validation errors
568 getErrors: function(value) {
570 errors = me.callParent(arguments),
571 validator = me.validator,
572 emptyText = me.emptyText,
573 allowBlank = me.allowBlank,
575 vtypes = Ext.form.field.VTypes,
577 format = Ext.String.format,
580 value = value || me.processRawValue(me.getRawValue());
582 if (Ext.isFunction(validator)) {
583 msg = validator.call(me, value);
589 if (value.length < 1 || value === emptyText) {
591 errors.push(me.blankText);
593 //if value is blank, there cannot be any additional errors
597 if (value.length < me.minLength) {
598 errors.push(format(me.minLengthText, me.minLength));
601 if (value.length > me.maxLength) {
602 errors.push(format(me.maxLengthText, me.maxLength));
606 if(!vtypes[vtype](value, me)){
607 errors.push(me.vtypeText || vtypes[vtype +'Text']);
611 if (regex && !regex.test(value)) {
612 errors.push(me.regexText || me.invalidText);
618 <span id='Ext-form-field-Text-method-selectText'> /**
619 </span> * Selects text in this field
620 * @param {Number} start (optional) The index where the selection should start (defaults to 0)
621 * @param {Number} end (optional) The index where the selection should end (defaults to the text length)
623 selectText : function(start, end){
625 v = me.getRawValue(),
631 if (v.length > 0) {
632 start = start === undef ? 0 : start;
633 end = end === undef ? v.length : end;
634 if (el.setSelectionRange) {
635 el.setSelectionRange(start, end);
637 else if(el.createTextRange) {
638 range = el.createTextRange();
639 range.moveStart('character', start);
640 range.moveEnd('character', end - v.length);
643 doFocus = Ext.isGecko || Ext.isOpera;
650 <span id='Ext-form-field-Text-method-autoSize'> /**
651 </span> * Automatically grows the field to accomodate the width of the text up to the maximum field width allowed.
652 * This only takes effect if <tt>{@link #grow} = true</tt>, and fires the {@link #autosize} event if the
655 autoSize: function() {
658 if (me.grow && me.rendered) {
659 me.doComponentLayout();
660 width = me.inputEl.getWidth();
661 if (width !== me.lastInputWidth) {
662 me.fireEvent('autosize', width);
663 me.lastInputWidth = width;
668 initAria: function() {
670 this.getActionEl().dom.setAttribute('aria-required', this.allowBlank === false);
673 <span id='Ext-form-field-Text-method-getBodyNaturalWidth'> /**
674 </span> * @protected override
675 * To get the natural width of the inputEl, we do a simple calculation based on the
676 * 'size' config. We use hard-coded numbers to approximate what browsers do natively,
677 * to avoid having to read any styles which would hurt performance.
679 getBodyNaturalWidth: function() {
680 return Math.round(this.size * 6.5) + 20;