flex中一个汉字做二个字节处理

众所周知textinput、textarea中有提供maxChars属性,控制输入字符的长度,但数据库中一般一个汉字点二个字节,此时,如果在界面处理长度,就需要做一个汉字做二个字节处理,就象jquery formValidator一样,在flex sdk4以上版本,提供了changing事件做处理,悲剧的是4以下版本没有这个事件,这样,就只好自己扩展StringValidator处理,以下给出完整代码

package com.common.util {


import mx.utils.StringUtil;
import mx.validators.StringValidator;
import mx.validators.ValidationResult;

/**
  * 自定义字符串检验器
  * @author chens
  * 引入汉字按照占有二个字节进行处理
  *
  */
public class CustomStringValidator extends StringValidator {
  private var _label:String;

  public function set label(label:String):void {
   this._label = label;
  }

  public function get label():String {
   return this._label;
  }

  override protected function doValidation(value:Object):Array {
   var results:Array = super.doValidation(value);

   // Return if there are errors
   // or if the required property is set to false and length is 0.
   var val:String = value ? String(value) : "";

   if (results.length > 0 || ((val.length == 0) && !required))
    return results;
   else
    return CustomStringValidator.validateString(this, value, null);
  }

  public static function validateString(validator:StringValidator, value:Object, baseField:String = null):Array {
   var results:Array = [];

   // Resource-backed properties of the validator.
   var maxLength:Number = Number(validator.maxLength);
   var minLength:Number = Number(validator.minLength);

   var val:String = value != null ? String(value) : "";

   /* 在这处理汉字占用的字节长度 */
   var target:* = validator.source;

   if (!isNaN(maxLength) && val.replace(/[^\x00-\xff]/g, "xx").length > maxLength) {
    results.push(new ValidationResult(true, baseField, "tooLong", target.label + '最多可输入' + maxLength + '个字符或' + (maxLength / 2) + '个汉字'));
    return results;
   }

   if (!isNaN(minLength) && val.length < minLength) {
    results.push(new ValidationResult(true, baseField, "tooShort", target.label + '至少输入' + minLength + '个字符或' + (minLength / 2 < 1 ? 1 : minLength / 2) + '个汉字'));
    return results;
   }

   return results;
  }

}
}

你可能感兴趣的:(Flex)