`

Ext扩展TriggerField实现唯一值校验

阅读更多

为了验证输入域的值为唯一值,扩展了Ext.form.TirggerField 实现Ajax方式的自定义验证输入域。原使用Ext.Ajax的内置方法,但Doc中对request方法的特别注释是:

 

Important: Ajax server requests are asynchronous, and this call will return before the response has been received. Process any returned data in a callback function.

To execute a callback function in the correct scope, use the scope option.

 

如上所说,Ajax服务请求是异步的,即函数会立即返回,然后是执行callback回调方法,这样就会产生时序问题,TriggerField的validator方法会首先接收到函数的undefined返回,这样验证就出现了错误,会误认为验证失败,但Ext.Ajax的config option中没有关于XMLHttpRequest使用异步还是同步的方式请求的设置。这样就没办法解决时序问题,所以改为使用Prototype的Ajax对象实现此功能,Prototype的Ajax中有asynchronous项属性来决定到底使用同步还是异步方式来请求,把asynchronous: false ,时序问题就迎刃而解了。

 

  Ext.ux.UniqueField = Ext.extend(Ext.form.TriggerField, {
			allowBlank: false,
			validateOnBlur: true,  
			invalidText: '此字段值需唯一!',
			validator: function() {
				uniqueFieldValidation(this);
				return valid;
			},
			onTriggerClick: function() {
				uniqueFieldValidation(this);
				return valid;
			}
		});

		var valid = '';
		function uniqueFieldValidation(element) {
			new Ajax.Request('dictionaryCodeValidation.do', {
					asynchronous: false,
					onSuccess: function(response) {
					var result = response.responseText.evalJSON();
					if(result.isUniqueCode) {
						valid = true;
						return;
					} else {
						valid = false;
						return;
					}
				},
				parameters: { dictionaryCode: $(element.getId()).value }
			});
		}
 
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics