Javascript ExtJs 依赖字段验证

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5186595/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 16:02:57  来源:igfitidea点击:

ExtJs dependent field validation

javascriptvalidationextjs

提问by fastcodejava

How do I validate one field which is dependent on another field?

如何验证依赖于另一个字段的一个字段?

{
  xtype:          'textfield',
  name:           'name2',
  vtype:          'type',      // how to write the validation code for this if it 
                               // depends on the value of another field?
  allowBlank:     false
}

回答by ChrisR

By adding your own custom validator and therein perform your validation.

通过添加您自己的自定义验证器并在其中执行您的验证。

var field_one = new Ext.form.TextField({
    name: 'field_one',
    fieldLabel: 'Field one'
});

var field_two = new Ext.form.TextField({
    name: 'field_two',
    fieldLabel: 'Field two',
    validator: function(value){
        if(field_one.getValue() != value) {
            return 'Error! Value not identical to field one';
        } else {
            return true;
        }
    }
});

回答by bensiu

field definition:

字段定义:

....
monitorValid:     true,
....
}, {
  xtype:          'textfield',
  name:           'name1',
  ref:            'name1',

}, {
  xtype:          'textfield',
  name:           'name2',
  ref:            'name2',
  allowBlank:     false,
....

next in initComponent (or listener if you preffer):

initComponent 中的下一个(或监听器,如果您愿意):

this.name2.on ( 'change', this._validate_name2, this );

and define handler in FormPanel:

并在 FormPanel 中定义处理程序:

this._validate_name2: function ( ) {
   if ( this.name1.getValue () == this.name2.getValue () ) {
      this.name2.markInvalid ( 'field does not match name1' );
      this.name2.setValue ( null );
   }
}

"markInvalid () method does not cause the Field's validate method to return false if the value does pass validation. So simply marking a Field as invalid will not prevent submission of forms submitted with the Ext.form.Action.Submit.clientValidation option set."

“如果值确实通过验证,markInvalid() 方法不会导致 Field 的验证方法返回 false。因此,简单地将 Field 标记为无效不会阻止提交使用 Ext.form.Action.Submit.clientValidation 选项集提交的表单。 ”

For this reason combination allowBlank and setValue ( null ) will break validation

出于这个原因,组合 allowBlank 和 setValue ( null ) 将破坏验证

回答by incutonez

I mocked up an example of how I'm doing this with comboboxes in Ext JS 5.1... it's easily portable to Ext 4 code, you'd just have to make use of initComponentinstead of ViewController's init. Here's the code (and Fiddle):

我嘲笑起来如何,我在Ext JS的5.1组合框这样一个例子......它很容易移植到分机4码,你只需要使用的initComponent,而不是视图控制器的init。这是代码(和Fiddle):

Ext.application({
  name: 'Fiddle',

  launch: function() {
    Ext.define('MyComboViewController', {
      extend: 'Ext.app.ViewController',
      alias: 'controller.mycombo',
      init: function() {
        this.getView().setStore(this.createStore());
      },
      createStore: function() {
        var store = Ext.create('Ext.data.Store', {
          fields: [
            {name: 'disp', type: 'string'},
            {name: 'val', type: 'int'}
          ],
          data: [
            {disp: 'One', val: 1},
            {disp: 'Two', val: 2},
            {disp: 'Three', val: 3},
            {disp: 'Four', val: 4},
            {disp: 'Five', val: 5}
          ],
          proxy: {
            type: 'memory'
          }
        });
        return store;
      }
    });

    Ext.define('MyCombo', {
      extend: 'Ext.form.field.ComboBox',
      xtype: 'myCombo',
      controller: 'mycombo',
      displayField: 'disp',
      valueField: 'val',
      labelAlign: 'top',
      validateOnChange: false,
      typeAhead: true,
      queryMode: 'local'
    });

    Ext.define('MyCombosContainerViewController', {
      extend: 'Ext.app.ViewController',
      alias: 'controller.mycomboscontainer',
      init: function() {
        var startCombo = this.lookupReference('startCombo');
        var endCombo = this.lookupReference('endCombo');
        startCombo.validator = Ext.bind(this.comboValidator, this, [startCombo, endCombo]);
        endCombo.validator = Ext.bind(this.comboValidator, this, [startCombo, endCombo]);
      },
      comboValidator: function(startCombo, endCombo) {
        return startCombo.getValue() < endCombo.getValue();
      },
      onSelectComboBox: function(combo) {
        var startCombo = this.lookupReference('startCombo');
        var endCombo = this.lookupReference('endCombo');
        startCombo.validate();
        endCombo.validate();
      }
    });

    Ext.define('MyCombosContainer', {
      extend: 'Ext.form.FieldContainer',
      controller: 'mycomboscontainer',
      layout: {
        type: 'hbox',
        align: 'stretch'
      },
      items: [{
        xtype: 'myCombo',
        reference: 'startCombo',
        fieldLabel: 'Start',
        listeners: {
          select: 'onSelectComboBox'
        }
      }, {
        xtype: 'myCombo',
        reference: 'endCombo',
        fieldLabel: 'End',
        listeners: {
          select: 'onSelectComboBox'
        }
      }]
    });

    Ext.create('MyCombosContainer', {
      renderTo: Ext.getBody()
    });
  }
});

回答by Sergey Novikov

To validate linked fields I usually create function (I add this to my Ext.lib.Validatorsclass so I can call it in whole application) that returns an anonymous function with preconfigured scope and validation logic (so I can use it multiple times across my application).

为了验证链接字段,我通常会创建函数(我将它添加到我的Ext.lib.Validators类中,以便我可以在整个应用程序中调用它),该函数返回一个具有预配置范围和验证逻辑的匿名函数(因此我可以在我的应用程序中多次使用它)。

Here is an example:

下面是一个例子:

myValidator: function (firstFieldSelector, secondFieldSelector, thirdFieldSelector) {
    return function () {
        var firstField = Ext.ComponentQuery.query(firstFieldSelector)[0],
            secondField= Ext.ComponentQuery.query(secondFieldSelector)[0],
            thirdField= Ext.ComponentQuery.query(thirdFieldSelector)[0];

        if (firstField && secondField && thirdField) {
            // Validation logic here...
            if( true ) {
                return true;
            } else {
                return 'Error text here...';
            }
        } else {
            // Validator incorrectly configured, do not validate with it
            return true;
        }
    }
}

And here is an example fiddlewith timespan selection.

这是一个使用时间跨度选择的示例小提琴

回答by Vineet

Generically - I would suggest to hook up change event listeners on all fields which needs to have cross validation. In change event handler we need to trigger validation on every other field which needs to validation with the field being modified. this approach works very well when you have a form and there are lots of fields and lots of validations needs to be done.

通常 - 我建议在需要交叉验证的所有字段上连接更改事件侦听器。在更改事件处理程序中,我们需要在需要使用被修改的字段进行验证的每个其他字段上触发验证。当您有一个表单并且有很多字段和很多验证需要完成时,这种方法非常有效。