regex - 使用正则表达式限制文本字段/数字字段中的输入字符?

标签 regex validation extjs

我在 ExtJS 表单中使用 numberField,并且只想输入 0-99 范围内的正数,并且它应该只接受 2 个字符(且不超过 2 个)。

{
    xtype:"textfield",
    allowNegative: false,
    allowDecimals: false,
    minValue: 0,
    maxValue: 99,
    maxLength: 2
}

上面的代码出错,但它接受超过 2 个字符。

我也尝试过以下但问题是相同的:

{
    xtype:"textfield",
    regex: /^\d{0,2}$/,
    regexText: "<b>Error</b></br>Invalid Number entered.",
    validator: function(v) {
        return /^\d{0,2}$/.test(v)?true:"Invalid Number";
    }
}

如何限制输入超过2个字符?

最佳答案

如果您使用的是版本 3,则 TextFieldmaxLength 文档描述了如何使用 autoCreate 属性来声明最大长度(文档示例显示了 NumberField,但 TextField 类也支持它):

maxLength : Number Maximum input field length allowed by validation (defaults to Number.MAX_VALUE). This behavior is intended to provide instant feedback to the user by improving usability to allow pasting and editing or overtyping and back tracking. To restrict the maximum number of characters that can be entered into the field use autoCreate to add any attributes you want to a field, for example:

var myField =
new Ext.form.NumberField({
     id: 'mobile',
     anchor:'90%',
     fieldLabel: 'Mobile',
     maxLength: 16, // for validation
     autoCreate: {tag: 'input', type: 'text', size: '20', autocomplete:
'off', maxlength: '10'} });

使用版本 4,文本字段具有 enforceMaxLength属性。

如果您决定使用正则表达式,两个版本都支持 maskRe 属性,尽管我认为这不会阻止粘贴无效值。

关于regex - 使用正则表达式限制文本字段/数字字段中的输入字符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7007957/

相关文章:

ruby-on-rails - 跳过相关对象的验证 - rails activerecord

javascript - 从 ExtJS Tree 获取所有加载的节点

python - 无法在正则表达式中检测到 '-' 字符

regex - 使用正则表达式在字符串开头提取美元金额

java - 如何在 lucene 中编写正则表达式模式?

java - Wicket 口和后端验证

jquery - 正则表达式 jQuery 验证

javascript - ExtJS 4 数据 View 问题

javascript - 如何使用 `document.querySelector()` 访问 ExtJS 元素?

php - preg_replace : add number after backreference