3 * Copyright(c) 2006-2010 Ext JS, Inc.
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){
426 * Uses getErrors to build an array of validation errors. If any errors are found, markInvalid is called
427 * with the first and false is returned, otherwise true is returned. Previously, subclasses were invited
428 * to provide an implementation of this to process validations - from 3.2 onwards getErrors should be
429 * overridden instead.
430 * @param {Mixed} The current value of the field
431 * @return {Boolean} True if all validations passed, false if one or more failed
433 validateValue : function(value) {
434 //currently, we only show 1 error at a time for a field, so just use the first one
435 var error = this.getErrors(value)[0];
437 if (error == undefined) {
440 this.markInvalid(error);
446 * Runs this field's validators and returns an array of error messages for any validation failures.
447 * This is called internally during validation and would not usually need to be used manually.
448 * Each subclass should override or augment the return value to provide their own errors
449 * @return {Array} All error messages for this field
451 getErrors: function() {
456 * Gets the active error message for this field.
457 * @return {String} Returns the active error message on the field, if there is no error, an empty string is returned.
459 getActiveError : function(){
460 return this.activeError || '';
464 * <p>Display an error message associated with this field, using {@link #msgTarget} to determine how to
465 * display the message and applying {@link #invalidClass} to the field's UI element.</p>
466 * <p><b>Note</b>: this method does not cause the Field's {@link #validate} method to return <code>false</code>
467 * if the value does <i>pass</i> validation. So simply marking a Field as invalid will not prevent
468 * submission of forms submitted with the {@link Ext.form.Action.Submit#clientValidation} option set.</p>
469 * {@link #isValid invalid}.
470 * @param {String} msg (optional) The validation message (defaults to {@link #invalidText})
472 markInvalid : function(msg){
473 //don't set the error icon if we're not rendered or marking is prevented
474 if (this.rendered && !this.preventMark) {
475 msg = msg || this.invalidText;
477 var mt = this.getMessageHandler();
480 }else if(this.msgTarget){
481 this.el.addClass(this.invalidClass);
482 var t = Ext.getDom(this.msgTarget);
485 t.style.display = this.msgDisplay;
490 this.setActiveError(msg);
494 * Clear any invalid styles/messages for this field
496 clearInvalid : function(){
497 //don't remove the error icon if we're not rendered or marking is prevented
498 if (this.rendered && !this.preventMark) {
499 this.el.removeClass(this.invalidClass);
500 var mt = this.getMessageHandler();
503 }else if(this.msgTarget){
504 this.el.removeClass(this.invalidClass);
505 var t = Ext.getDom(this.msgTarget);
508 t.style.display = 'none';
513 this.unsetActiveError();
517 * Sets the current activeError to the given string. Fires the 'invalid' event.
518 * This does not set up the error icon, only sets the message and fires the event. To show the error icon,
519 * use markInvalid instead, which calls this method internally
520 * @param {String} msg The error message
521 * @param {Boolean} suppressEvent True to suppress the 'invalid' event from being fired
523 setActiveError: function(msg, suppressEvent) {
524 this.activeError = msg;
525 if (suppressEvent !== true) this.fireEvent('invalid', this, msg);
529 * Clears the activeError and fires the 'valid' event. This is called internally by clearInvalid and would not
530 * usually need to be called manually
531 * @param {Boolean} suppressEvent True to suppress the 'invalid' event from being fired
533 unsetActiveError: function(suppressEvent) {
534 delete this.activeError;
535 if (suppressEvent !== true) this.fireEvent('valid', this);
539 getMessageHandler : function(){
540 return Ext.form.MessageTargets[this.msgTarget];
544 getErrorCt : function(){
545 return this.el.findParent('.x-form-element', 5, true) || // use form element wrap if available
546 this.el.findParent('.x-form-field-wrap', 5, true); // else direct field wrap
549 // Alignment for 'under' target
550 alignErrorEl : function(){
551 this.errorEl.setWidth(this.getErrorCt().getWidth(true) - 20);
554 // Alignment for 'side' target
555 alignErrorIcon : function(){
556 this.errorIcon.alignTo(this.el, 'tl-tr', [2, 0]);
560 * Returns the raw data value which may or may not be a valid, defined value. To return a normalized value see {@link #getValue}.
561 * @return {Mixed} value The field value
563 getRawValue : function(){
564 var v = this.rendered ? this.el.getValue() : Ext.value(this.value, '');
565 if(v === this.emptyText){
572 * Returns the normalized data value (undefined or emptyText will be returned as ''). To return the raw value see {@link #getRawValue}.
573 * @return {Mixed} value The field value
575 getValue : function(){
579 var v = this.el.getValue();
580 if(v === this.emptyText || v === undefined){
587 * Sets the underlying DOM field's value directly, bypassing validation. To set the value with validation see {@link #setValue}.
588 * @param {Mixed} value The value to set
589 * @return {Mixed} value The field value that is set
591 setRawValue : function(v){
592 return this.rendered ? (this.el.dom.value = (Ext.isEmpty(v) ? '' : v)) : '';
596 * Sets a data value into the field and validates it. To set the value directly without validation see {@link #setRawValue}.
597 * @param {Mixed} value The value to set
598 * @return {Ext.form.Field} this
600 setValue : function(v){
603 this.el.dom.value = (Ext.isEmpty(v) ? '' : v);
609 // private, does not work for all fields
610 append : function(v){
611 this.setValue([this.getValue(), v].join(''));
615 * @cfg {Boolean} autoWidth @hide
618 * @cfg {Boolean} autoHeight @hide
622 * @cfg {String} autoEl @hide
627 Ext.form.MessageTargets = {
629 mark: function(field, msg){
630 field.el.addClass(field.invalidClass);
631 field.el.dom.qtip = msg;
632 field.el.dom.qclass = 'x-form-invalid-tip';
633 if(Ext.QuickTips){ // fix for floating editors interacting with DND
634 Ext.QuickTips.enable();
637 clear: function(field){
638 field.el.removeClass(field.invalidClass);
639 field.el.dom.qtip = '';
643 mark: function(field, msg){
644 field.el.addClass(field.invalidClass);
645 field.el.dom.title = msg;
647 clear: function(field){
648 field.el.dom.title = '';
652 mark: function(field, msg){
653 field.el.addClass(field.invalidClass);
655 var elp = field.getErrorCt();
656 if(!elp){ // field has no container el
657 field.el.dom.title = msg;
660 field.errorEl = elp.createChild({cls:'x-form-invalid-msg'});
661 field.on('resize', field.alignErrorEl, field);
662 field.on('destroy', function(){
663 Ext.destroy(this.errorEl);
666 field.alignErrorEl();
667 field.errorEl.update(msg);
668 Ext.form.Field.msgFx[field.msgFx].show(field.errorEl, field);
670 clear: function(field){
671 field.el.removeClass(field.invalidClass);
673 Ext.form.Field.msgFx[field.msgFx].hide(field.errorEl, field);
675 field.el.dom.title = '';
680 mark: function(field, msg){
681 field.el.addClass(field.invalidClass);
682 if(!field.errorIcon){
683 var elp = field.getErrorCt();
684 // field has no container el
686 field.el.dom.title = msg;
689 field.errorIcon = elp.createChild({cls:'x-form-invalid-icon'});
691 field.ownerCt.on('afterlayout', field.alignErrorIcon, field);
692 field.ownerCt.on('expand', field.alignErrorIcon, field);
694 field.on('resize', field.alignErrorIcon, field);
695 field.on('destroy', function(){
696 Ext.destroy(this.errorIcon);
699 field.alignErrorIcon();
700 field.errorIcon.dom.qtip = msg;
701 field.errorIcon.dom.qclass = 'x-form-invalid-tip';
702 field.errorIcon.show();
704 clear: function(field){
705 field.el.removeClass(field.invalidClass);
707 field.errorIcon.dom.qtip = '';
708 field.errorIcon.hide();
710 field.el.dom.title = '';
716 // anything other than normal should be considered experimental
717 Ext.form.Field.msgFx = {
719 show: function(msgEl, f){
720 msgEl.setDisplayed('block');
723 hide : function(msgEl, f){
724 msgEl.setDisplayed(false).update('');
729 show: function(msgEl, f){
730 msgEl.slideIn('t', {stopFx:true});
733 hide : function(msgEl, f){
734 msgEl.slideOut('t', {stopFx:true,useDisplay:true});
739 show: function(msgEl, f){
741 msgEl.alignTo(f.el, 'tl-tr');
742 msgEl.slideIn('l', {stopFx:true});
745 hide : function(msgEl, f){
746 msgEl.slideOut('l', {stopFx:true,useDisplay:true});
750 Ext.reg('field', Ext.form.Field);