在 input
输入框上使用正则限制用户的输入。
和原生的输入框完全一致(除了会限制输入):
- 支持任意原生属性,比如:
maxlength
class
- 支持
v-model
- 支持所有的原生事件:
change
、blur
等等
简体中文 | English
点击此处: Live Demo.
项目目录结构如下:
vue-pattern-input/
├── ...
├── src/
│ └── /component
│ └── pattern-input.vue // core
└── /view
└── demo.html
Parameter | Type | Default | Required | Description |
---|---|---|---|---|
regExp | RegExp | null | false | Using for: String.prototype.replace(regexp, replacement) |
replacement | String | '' | false | Using for: String.prototype.replace(regexp, replacement) |
v-model[.number] | String/Number | true | Using for getting input value |
regExp | Description |
---|---|
/^[0\D]*|\D*/g | 只能输入正整数 |
/[^a-z]/g | 只能输入小写字母 |
/[^A-Z]/g | 只能输入大写字母 |
/[^\w]/g | 只能输入 \w, 即 [A-Za-z0-9_] |
/[^\u4e00-\u9fa5]/g | 只能输入中文 |
setting: {
regExp: /^[0\D]*|\D*/g, // Match any character that doesn't belong to the positive integer
replacement: '',
val: '223'
}
<pattern-input class="your-class-name"
:regExp="setting.regExp"
:replacement="setting.replacement"
@input="handleInput"
@change="handleChange"
v-model.number="setting.val"></pattern-input>
This setting will make user input positive integer only.
When you want get a Number, remember use
v-model.number
, and the safe maxlength is 15.
- v3.0.0 开始支持 Vue3.0;如果使用 Vue2.x 请切到 v2.x
- Use immediate watch
I'm not sure is it necessary to emit all the input events. Now I only emitinput
andchange
events.- Now, you can bind any native event on input !
<pattern-input ... @change="onChange" @blur="onBlur" @focus="onFocus" ...etc ...</pattern-input>
- Required:
- Vue: v2.4.0+, because it use $listeners
Have a bug or a feature request? If your problem or idea is not addressed yet, please open a new issue.
I'm not sure is it necessary to emit all the input events. Now I only emit input
and change
events.
我觉得现在这种正则限制输入并不是很好,感觉怪怪的。 可能所需要写的正则是去除所不需要的字符,而不是所需要的字符吧。
Code released under the MIT License.