项目中使用 Vue + elementUi 搭建后台管理系统,在输入框进行数字校验的时候不知为何官网的方法不起作用,只能用了个迂回的方法。
官网的方法:
<el-form :model="ruleForm" status-icon :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
<el-form-item label="年龄" prop="age">
<el-input v-model.number="ruleForm.age"></el-input>
</el-form-item>
<el-form-item>
<el-button type="primary" @click="submitForm('ruleForm')">提交</el-button>
<el-button @click="resetForm('ruleForm')">重置</el-button>
</el-form-item>
</el-form>
<script>
export default {
data() {
var checkAge = (rule, value, callback) => {
if (!value) {
return callback(new Error('年龄不能为空'));
}
setTimeout(() => {
if (!Number.isInteger(value)) {
callback(new Error('请输入数字值'));
} else {
if (value < 18) {
callback(new Error('必须年满18岁'));
} else {
callback();
}
}
}, 1000);
};
return {
ruleForm: {
age: ''
},
rules: {
age: [
{ validator: checkAge, trigger: 'blur' }
]
}
};
},
methods: {
submitForm(formName) {
this.$refs[formName].validate((valid) => {
if (valid) {
alert('submit!');
} else {
console.log('error submit!!');
return false;
}
});
},
resetForm(formName) {
this.$refs[formName].resetFields();
}
}
}
</script>
自己的方法:
<el-form-item label="年龄" prop="age">
<el-input v-model="ruleForm.age" @keyup.native="handleKeyUp($event)"></el-input>
</el-form-item>
rules: {
age: [
{ required: true, message: '年龄不能为空', trigger: 'blur' },
{message: '请输入数字值', pattern: /^[0-9]*[1-9][0-9]*$/}
]
}
methods: {
handleKeyUp(e) {
let keynum = window.event ? e.keyCode : e.which; // 获取键盘码
let keychar = String.fromCharCode(keynum); // 获取键盘码对应字符
if (keynum === 189 || keynum === 190 || keynum === 109) {
this.$message.warning('禁止输入小数以及负数');
e.target.value = ''
}
},
}