<span style="font-family: Arial, Helvetica, sans-serif; background-color: rgb(255, 255, 255);">系统使用Txtjs5自带的HtmlEditor文本编辑器,数据库对应字段长度最大为200,文本编辑时,稍微加点样式就超出限制了。</span>
要求:在前端验证输入长度,如果输入过长,则提示,并无法提交。
HtmlEditor的并没有提供像Text中可以设置MaxLength的配置。
看HtmlEditor的源码会发现,HtmlEditor继承了Filed类,Field中有属性:
Ext.define('Ext.form.field.Field', {
mixinId: 'field',
/**
* @property {Boolean} isFormField
* Flag denoting that this component is a Field. Always true.
*/
isFormField : true,
config: {
/**
* @cfg {Boolean/String} validation
* This property, when a `String`, contributes its value to the error state of this
* instance as reported by `getErrors`. This property is implicitly bound when the
* `value` of this field is bound based on `{@link Ext.Component#modelValidation}`.
*/
validation: null
},
并且Field有方法:isValid()
isValid : function() {
var me = this;
return me.disabled || Ext.isEmpty(me.getErrors());
},
/**
* Returns whether or not the field value is currently valid by {@link #getErrors validating} the field's current
* value, and fires the {@link #validitychange} event if the field's validity has changed since the last validation.
* **Note**: {@link #disabled} fields are always treated as valid.
*
* Custom implementations of this method are allowed to have side-effects such as triggering error message display.
* To validate without side-effects, use {@link #isValid}.
*
* @return {Boolean} True if the value is valid, else false
*/
validate : function() {
var me = this,
isValid = me.isValid();
if (isValid !== me.wasValid) {
me.wasValid = isValid;
me.fireEvent('validitychange', me, isValid);
}
return isValid;
},
isValid()!!有没有很熟悉。
form.isValid()~不知道form验证的时候会不会跟这个有关系?
抱着试试看的态度,在HtmlEditor输入发生变化的时候,修改了Validation配置,并在超出200(我们项目要求是200)后,做了提示:
change: {
fn: function(editor, newValue, oldValue, eOpts) {
if(newValue.length >= 200){
editor.setValidation('最大输入限制200');
editor.setActiveError('最大输入限制200');
}else{
editor.setValidation(null);
editor.setActiveError();
}
},
scope: me
},
blur: { //在源码编辑模式下onchange事件不起作用,在失去焦点的时候判断。
fn: function(editor) {
if(editor.getValue().length >= 200){
editor.setValidation('最大输入限制200');
editor.setActiveError('最大输入限制200');
}else{
editor.setValidation(null);
editor.setActiveError();
}
},
scope: me
}
然后输入超出200.提示出来了,而且from没有提交。偶也~
ps:绑定blur事件,是因为在源码编辑状态输入时,不知道为什么HtmlEditor的change事件失效了,所以只好在失去焦点的时候进行判断。
据说HtmlEditor的blur事件也失效,同事自己写的。那些我就不懂了。