3 * Copyright(c) 2006-2009 Ext JS, LLC
5 * http://www.extjs.com/license
8 * @class Ext.form.Field
9 * @extends Ext.BoxComponent
10 * Base class for form fields that provides default event handling, sizing, value handling and other functionality.
13 * @param {Object} config Configuration options
16 Ext.form.Field = Ext.extend(Ext.BoxComponent, {
18 * <p>The label Element associated with this Field. <b>Only available after this Field has been rendered by a
19 * {@link form Ext.layout.FormLayout} layout manager.</b></p>
24 * @cfg {String} inputType The type attribute for input fields -- e.g. radio, text, password, file (defaults
25 * to 'text'). The types 'file' and 'password' must be used to render those field types currently -- there are
26 * no separate Ext components for those. Note that if you use <tt>inputType:'file'</tt>, {@link #emptyText}
27 * is not supported and should be avoided.
30 * @cfg {Number} tabIndex The tabIndex for this field. Note this only applies to fields that are rendered,
31 * not those which are built via applyTo (defaults to undefined).
34 * @cfg {Mixed} value A value to initialize this field with (defaults to undefined).
37 * @cfg {String} name The field's HTML name attribute (defaults to '').
38 * <b>Note</b>: this property must be set if this field is to be automatically included with
39 * {@link Ext.form.BasicForm#submit form submit()}.
42 * @cfg {String} cls A custom CSS class to apply to the field's underlying element (defaults to '').
46 * @cfg {String} invalidClass The CSS class to use when marking a field invalid (defaults to 'x-form-invalid')
48 invalidClass : 'x-form-invalid',
50 * @cfg {String} invalidText The error text to use when marking a field invalid and no message is provided
51 * (defaults to 'The value in this field is invalid')
53 invalidText : 'The value in this field is invalid',
55 * @cfg {String} focusClass The CSS class to use when the field receives focus (defaults to 'x-form-focus')
57 focusClass : 'x-form-focus',
59 * @cfg {Boolean} preventMark
60 * <tt>true</tt> to disable {@link #markInvalid marking the field invalid}.
61 * Defaults to <tt>false</tt>.
64 * @cfg {String/Boolean} validationEvent The event that should initiate field validation. Set to false to disable
65 automatic validation (defaults to 'keyup').
67 validationEvent : 'keyup',
69 * @cfg {Boolean} validateOnBlur Whether the field should validate when it loses focus (defaults to true).
71 validateOnBlur : true,
73 * @cfg {Number} validationDelay The length of time in milliseconds after user input begins until validation
74 * is initiated (defaults to 250)
76 validationDelay : 250,
78 * @cfg {String/Object} autoCreate <p>A {@link Ext.DomHelper DomHelper} element spec, or true for a default
79 * element spec. Used to create the {@link Ext.Component#getEl Element} which will encapsulate this Component.
80 * See <tt>{@link Ext.Component#autoEl autoEl}</tt> for details. Defaults to:</p>
81 * <pre><code>{tag: 'input', type: 'text', size: '20', autocomplete: 'off'}</code></pre>
83 defaultAutoCreate : {tag: 'input', type: 'text', size: '20', autocomplete: 'off'},
85 * @cfg {String} fieldClass The default CSS class for the field (defaults to 'x-form-field')
87 fieldClass : 'x-form-field',
89 * @cfg {String} msgTarget<p>The location where the message text set through {@link #markInvalid} should display.
90 * Must be one of the following values:</p>
91 * <div class="mdetail-params"><ul>
92 * <li><code>qtip</code> Display a quick tip containing the message when the user hovers over the field. This is the default.
93 * <div class="subdesc"><b>{@link Ext.QuickTips#init Ext.QuickTips.init} must have been called for this setting to work.</b></div</li>
94 * <li><code>title</code> Display the message in a default browser title attribute popup.</li>
95 * <li><code>under</code> Add a block div beneath the field containing the error message.</li>
96 * <li><code>side</code> Add an error icon to the right of the field, displaying the message in a popup on hover.</li>
97 * <li><code>[element id]</code> Add the error message directly to the innerHTML of the specified element.</li>
102 * @cfg {String} msgFx <b>Experimental</b> The effect used when displaying a validation message under the field
103 * (defaults to 'normal').
107 * @cfg {Boolean} readOnly <tt>true</tt> to mark the field as readOnly in HTML
108 * (defaults to <tt>false</tt>).
109 * <br><p><b>Note</b>: this only sets the element's readOnly DOM attribute.
110 * Setting <code>readOnly=true</code>, for example, will not disable triggering a
111 * ComboBox or DateField; it gives you the option of forcing the user to choose
112 * via the trigger without typing in the text box. To hide the trigger use
113 * <code>{@link Ext.form.TriggerField#hideTrigger hideTrigger}</code>.</p>
117 * @cfg {Boolean} disabled True to disable the field (defaults to false).
118 * <p>Be aware that conformant with the <a href="http://www.w3.org/TR/html401/interact/forms.html#h-17.12.1">HTML specification</a>,
119 * disabled Fields will not be {@link Ext.form.BasicForm#submit submitted}.</p>
123 * @cfg {Boolean} submitValue False to clear the name attribute on the field so that it is not submitted during a form post.
124 * Defaults to <tt>true</tt>.
138 initComponent : function(){
139 Ext.form.Field.superclass.initComponent.call(this);
143 * Fires when this field receives input focus.
144 * @param {Ext.form.Field} this
149 * Fires when this field loses input focus.
150 * @param {Ext.form.Field} this
155 * Fires when any key related to navigation (arrows, tab, enter, esc, etc.) is pressed.
156 * To handle other keys see {@link Ext.Panel#keys} or {@link Ext.KeyMap}.
157 * You can check {@link Ext.EventObject#getKey} to determine which key was pressed.
158 * For example: <pre><code>
159 var form = new Ext.form.FormPanel({
162 fieldLabel: 'Field 1',
166 fieldLabel: 'Field 2',
169 specialkey: function(field, e){
170 // e.HOME, e.END, e.PAGE_UP, e.PAGE_DOWN,
171 // e.TAB, e.ESC, arrow keys: e.LEFT, e.RIGHT, e.UP, e.DOWN
172 if (e.{@link Ext.EventObject#getKey getKey()} == e.ENTER) {
173 var form = field.ownerCt.getForm();
183 * @param {Ext.form.Field} this
184 * @param {Ext.EventObject} e The event object
189 * Fires just before the field blurs if the field value has changed.
190 * @param {Ext.form.Field} this
191 * @param {Mixed} newValue The new value
192 * @param {Mixed} oldValue The original value
197 * Fires after the field has been marked as invalid.
198 * @param {Ext.form.Field} this
199 * @param {String} msg The validation message
204 * Fires after the field has been validated with no errors.
205 * @param {Ext.form.Field} this
212 * Returns the {@link Ext.form.Field#name name} or {@link Ext.form.ComboBox#hiddenName hiddenName}
213 * attribute of the field if available.
214 * @return {String} name The field {@link Ext.form.Field#name name} or {@link Ext.form.ComboBox#hiddenName hiddenName}
216 getName : function(){
217 return this.rendered && this.el.dom.name ? this.el.dom.name : this.name || this.id || '';
221 onRender : function(ct, position){
223 var cfg = this.getAutoCreate();
226 cfg.name = this.name || this.id;
229 cfg.type = this.inputType;
233 Ext.form.Field.superclass.onRender.call(this, ct, position);
234 if(this.submitValue === false){
235 this.el.dom.removeAttribute('name');
237 var type = this.el.dom.type;
239 if(type == 'password'){
242 this.el.addClass('x-form-'+type);
245 this.setReadOnly(true);
247 if(this.tabIndex !== undefined){
248 this.el.dom.setAttribute('tabIndex', this.tabIndex);
251 this.el.addClass([this.fieldClass, this.cls]);
255 getItemCt : function(){
260 initValue : function(){
261 if(this.value !== undefined){
262 this.setValue(this.value);
263 }else if(!Ext.isEmpty(this.el.dom.value) && this.el.dom.value != this.emptyText){
264 this.setValue(this.el.dom.value);
267 * The original value of the field as configured in the {@link #value} configuration, or
268 * as loaded by the last form load operation if the form's {@link Ext.form.BasicForm#trackResetOnLoad trackResetOnLoad}
269 * setting is <code>true</code>.
271 * @property originalValue
273 this.originalValue = this.getValue();
277 * <p>Returns true if the value of this Field has been changed from its original value.
278 * Will return false if the field is disabled or has not been rendered yet.</p>
279 * <p>Note that if the owning {@link Ext.form.BasicForm form} was configured with
280 * {@link Ext.form.BasicForm}.{@link Ext.form.BasicForm#trackResetOnLoad trackResetOnLoad}
281 * then the <i>original value</i> is updated when the values are loaded by
282 * {@link Ext.form.BasicForm}.{@link Ext.form.BasicForm#setValues setValues}.</p>
283 * @return {Boolean} True if this field has been changed from its original value (and
284 * is not disabled), false otherwise.
286 isDirty : function() {
287 if(this.disabled || !this.rendered) {
290 return String(this.getValue()) !== String(this.originalValue);
294 * Sets the read only state of this field.
295 * @param {Boolean} readOnly Whether the field should be read only.
297 setReadOnly : function(readOnly){
299 this.el.dom.readOnly = readOnly;
301 this.readOnly = readOnly;
305 afterRender : function(){
306 Ext.form.Field.superclass.afterRender.call(this);
312 fireKey : function(e){
313 if(e.isSpecialKey()){
314 this.fireEvent('specialkey', this, e);
319 * Resets the current field value to the originally loaded value and clears any validation messages.
320 * See {@link Ext.form.BasicForm}.{@link Ext.form.BasicForm#trackResetOnLoad trackResetOnLoad}
323 this.setValue(this.originalValue);
328 initEvents : function(){
329 this.mon(this.el, Ext.EventManager.useKeydown ? 'keydown' : 'keypress', this.fireKey, this);
330 this.mon(this.el, 'focus', this.onFocus, this);
332 // standardise buffer across all browsers + OS-es for consistent event order.
333 // (the 10ms buffer for Editors fixes a weird FF/Win editor issue when changing OS window focus)
334 this.mon(this.el, 'blur', this.onBlur, this, this.inEditor ? {buffer:10} : null);
338 preFocus: Ext.emptyFn,
341 onFocus : function(){
344 this.el.addClass(this.focusClass);
347 this.hasFocus = true;
349 * <p>The value that the Field had at the time it was last focused. This is the value that is passed
350 * to the {@link #change} event which is fired if the value has been changed when the Field is blurred.</p>
351 * <p><b>This will be undefined until the Field has been visited.</b> Compare {@link #originalValue}.</p>
353 * @property startValue
355 this.startValue = this.getValue();
356 this.fireEvent('focus', this);
361 beforeBlur : Ext.emptyFn,
367 this.el.removeClass(this.focusClass);
369 this.hasFocus = false;
370 if(this.validationEvent !== false && (this.validateOnBlur || this.validationEvent == 'blur')){
373 var v = this.getValue();
374 if(String(v) !== String(this.startValue)){
375 this.fireEvent('change', this, v, this.startValue);
377 this.fireEvent('blur', this);
382 postBlur : Ext.emptyFn,
385 * Returns whether or not the field value is currently valid by
386 * {@link #validateValue validating} the {@link #processValue processed value}
387 * of the field. <b>Note</b>: {@link #disabled} fields are ignored.
388 * @param {Boolean} preventMark True to disable marking the field invalid
389 * @return {Boolean} True if the value is valid, else false
391 isValid : function(preventMark){
395 var restore = this.preventMark;
396 this.preventMark = preventMark === true;
397 var v = this.validateValue(this.processValue(this.getRawValue()));
398 this.preventMark = restore;
403 * Validates the field value
404 * @return {Boolean} True if the value is valid, else false
406 validate : function(){
407 if(this.disabled || this.validateValue(this.processValue(this.getRawValue()))){
415 * This method should only be overridden if necessary to prepare raw values
416 * for validation (see {@link #validate} and {@link #isValid}). This method
417 * is expected to return the processed value for the field which will
418 * be used for validation (see validateValue method).
419 * @param {Mixed} value
421 processValue : function(value){
427 * Subclasses should provide the validation implementation by overriding this
428 * @param {Mixed} value
430 validateValue : function(value){
435 * Gets the active error message for this field.
436 * @return {String} Returns the active error message on the field, if there is no error, an empty string is returned.
438 getActiveError : function(){
439 return this.activeError || '';
443 * <p>Display an error message associated with this field, using {@link #msgTarget} to determine how to
444 * display the message and applying {@link #invalidClass} to the field's UI element.</p>
445 * <p><b>Note</b>: this method does not cause the Field's {@link #validate} method to return <code>false</code>
446 * if the value does <i>pass</i> validation. So simply marking a Field as invalid will not prevent
447 * submission of forms submitted with the {@link Ext.form.Action.Submit#clientValidation} option set.</p>
448 * {@link #isValid invalid}.
449 * @param {String} msg (optional) The validation message (defaults to {@link #invalidText})
451 markInvalid : function(msg){
452 if(!this.rendered || this.preventMark){ // not rendered
455 msg = msg || this.invalidText;
457 var mt = this.getMessageHandler();
460 }else if(this.msgTarget){
461 this.el.addClass(this.invalidClass);
462 var t = Ext.getDom(this.msgTarget);
465 t.style.display = this.msgDisplay;
468 this.activeError = msg;
469 this.fireEvent('invalid', this, msg);
473 * Clear any invalid styles/messages for this field
475 clearInvalid : function(){
476 if(!this.rendered || this.preventMark){ // not rendered
479 this.el.removeClass(this.invalidClass);
480 var mt = this.getMessageHandler();
483 }else if(this.msgTarget){
484 this.el.removeClass(this.invalidClass);
485 var t = Ext.getDom(this.msgTarget);
488 t.style.display = 'none';
491 delete this.activeError;
492 this.fireEvent('valid', this);
496 getMessageHandler : function(){
497 return Ext.form.MessageTargets[this.msgTarget];
501 getErrorCt : function(){
502 return this.el.findParent('.x-form-element', 5, true) || // use form element wrap if available
503 this.el.findParent('.x-form-field-wrap', 5, true); // else direct field wrap
507 alignErrorIcon : function(){
508 this.errorIcon.alignTo(this.el, 'tl-tr', [2, 0]);
512 * Returns the raw data value which may or may not be a valid, defined value. To return a normalized value see {@link #getValue}.
513 * @return {Mixed} value The field value
515 getRawValue : function(){
516 var v = this.rendered ? this.el.getValue() : Ext.value(this.value, '');
517 if(v === this.emptyText){
524 * Returns the normalized data value (undefined or emptyText will be returned as ''). To return the raw value see {@link #getRawValue}.
525 * @return {Mixed} value The field value
527 getValue : function(){
531 var v = this.el.getValue();
532 if(v === this.emptyText || v === undefined){
539 * Sets the underlying DOM field's value directly, bypassing validation. To set the value with validation see {@link #setValue}.
540 * @param {Mixed} value The value to set
541 * @return {Mixed} value The field value that is set
543 setRawValue : function(v){
544 return this.rendered ? (this.el.dom.value = (Ext.isEmpty(v) ? '' : v)) : '';
548 * Sets a data value into the field and validates it. To set the value directly without validation see {@link #setRawValue}.
549 * @param {Mixed} value The value to set
550 * @return {Ext.form.Field} this
552 setValue : function(v){
555 this.el.dom.value = (Ext.isEmpty(v) ? '' : v);
561 // private, does not work for all fields
562 append : function(v){
563 this.setValue([this.getValue(), v].join(''));
567 * @cfg {Boolean} autoWidth @hide
570 * @cfg {Boolean} autoHeight @hide
574 * @cfg {String} autoEl @hide
579 Ext.form.MessageTargets = {
581 mark: function(field, msg){
582 field.el.addClass(field.invalidClass);
583 field.el.dom.qtip = msg;
584 field.el.dom.qclass = 'x-form-invalid-tip';
585 if(Ext.QuickTips){ // fix for floating editors interacting with DND
586 Ext.QuickTips.enable();
589 clear: function(field){
590 field.el.removeClass(field.invalidClass);
591 field.el.dom.qtip = '';
595 mark: function(field, msg){
596 field.el.addClass(field.invalidClass);
597 field.el.dom.title = msg;
599 clear: function(field){
600 field.el.dom.title = '';
604 mark: function(field, msg){
605 field.el.addClass(field.invalidClass);
607 var elp = field.getErrorCt();
608 if(!elp){ // field has no container el
609 field.el.dom.title = msg;
612 field.errorEl = elp.createChild({cls:'x-form-invalid-msg'});
613 field.errorEl.setWidth(elp.getWidth(true)-20);
615 field.errorEl.update(msg);
616 Ext.form.Field.msgFx[field.msgFx].show(field.errorEl, field);
618 clear: function(field){
619 field.el.removeClass(field.invalidClass);
621 Ext.form.Field.msgFx[field.msgFx].hide(field.errorEl, field);
623 field.el.dom.title = '';
628 mark: function(field, msg){
629 field.el.addClass(field.invalidClass);
630 if(!field.errorIcon){
631 var elp = field.getErrorCt();
632 if(!elp){ // field has no container el
633 field.el.dom.title = msg;
636 field.errorIcon = elp.createChild({cls:'x-form-invalid-icon'});
638 field.alignErrorIcon();
639 field.errorIcon.dom.qtip = msg;
640 field.errorIcon.dom.qclass = 'x-form-invalid-tip';
641 field.errorIcon.show();
642 field.on('resize', field.alignErrorIcon, field);
644 clear: function(field){
645 field.el.removeClass(field.invalidClass);
647 field.errorIcon.dom.qtip = '';
648 field.errorIcon.hide();
649 field.un('resize', field.alignErrorIcon, field);
651 field.el.dom.title = '';
657 // anything other than normal should be considered experimental
658 Ext.form.Field.msgFx = {
660 show: function(msgEl, f){
661 msgEl.setDisplayed('block');
664 hide : function(msgEl, f){
665 msgEl.setDisplayed(false).update('');
670 show: function(msgEl, f){
671 msgEl.slideIn('t', {stopFx:true});
674 hide : function(msgEl, f){
675 msgEl.slideOut('t', {stopFx:true,useDisplay:true});
680 show: function(msgEl, f){
682 msgEl.alignTo(f.el, 'tl-tr');
683 msgEl.slideIn('l', {stopFx:true});
686 hide : function(msgEl, f){
687 msgEl.slideOut('l', {stopFx:true,useDisplay:true});
691 Ext.reg('field', Ext.form.Field);