ExtJS4: How to show validation error message next to textbox, combobox etc

前端 未结 6 795
旧巷少年郎
旧巷少年郎 2020-12-29 08:05

I need to implement validation messages that appear right next to invalid field. Any help would be appreciated.

6条回答
  •  情书的邮戳
    2020-12-29 08:41

    The msgTarget: 'elementId' can work, but it seem very limited, particularly when you want multiple instances of one reusable ExtJs component (and therefor multiple instances of the same msgTarget element). For example I have an MDI style editor where you can open multiple editors of one type in a tab interface. It also doesn't seem to work with itemId or recognize DOM/container hierarchy.

    I therefor prefer to turn off the default handling if I don't want exactly one of the built in message display options by setting msgTarget: none and then performing my own message display by handling the fielderrorchange event which is designed for exactly this scenario. In this case I can now respect hierarchy of my forms even with multiple instances of the same editor form as I can select the error display element relative to the editor.

    Here's how I do it:

    {
        xtype: 'fieldcontainer',
        fieldLabel: 'My Field Label',
        layout: 'hbox',   // this will be container with 2 elements: the editor & the error
        items: [{
            xtype: 'numberfield',
            itemId: 'myDataFieldName',
            name: 'myDataFieldName',
            width: 150,
            msgTarget: 'none',  // don't use the default built in error message display
            validator: function (value) {
                return 'This is my custom validation message. All real validation logic removed for example clarity.';
            }
        }, {
            xtype: 'label',
            itemId: 'errorBox', // This ID lets me find the display element relative to the editor above
            cls: 'errorBox'     // This class lets me customize the appearance of the error element in CSS
        }],
        listeners: {
            'fielderrorchange': function (container, field, error, eOpts) {
                var errUI = container.down('#errorBox');
                if (error) {
                    // show error element, don't esape any HTML formatting provided
                    errUI.setText(error, false);
                    errUI.show();
                } else {
                    // hide error element
                    errUI.hide();
                }
            }
        }
    }
    

提交回复
热议问题