AI智能
改变未来

Element-ui 中表单(Form)验证数字值范围(大小)

方法一: 通过正则表达式实现

<template><div><el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm"><el-row><el-col :span="6"><el-form-item label="金额" prop="money"><el-input v-model.number="ruleForm.money"></el-input></el-form-item></el-col></el-row><el-row><el-col :span="6" style="text-align:center"><el-form-item><el-button type="primary" @click="submitForm('ruleForm')">提交</el-button></el-form-item></el-col></el-row></el-form></div></template><script>export default {data() {return {ruleForm: {money:'',},rules: {money:[{ required: true, message: '金额不能为空'},{ type: 'number', message: '金额必须为数字值'}, // 且不包括小数{ pattern: /^([0-9]|[1-9]\\d|1\\d\\d|2[0-4]\\d|25[0-5])$/, message: '范围在0-255',trigger: 'blur'}/*范围0-255分析:0-9:      [0-9]10-99:    [1-9]\\d100-199:   1\\d\\d200-249:   2[0-4]\\d250-255:   25[0-5]*/],}};},methods: {submitForm(formName) {this.$refs[formName].validate((valid) => {if (valid) {alert('成功');} else {return false;}});},}}</script>

补充:正则表达式相关知识点


方法二:自定义校验规则

<template><div><el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm"><el-row><el-col :span="6"><el-form-item label="金额" prop="money"><el-input v-model.number="ruleForm.money"></el-input></el-form-item></el-col></el-row><el-row><el-col :span="6" style="text-align:center"><el-form-item><el-button type="primary" @click="submitForm('ruleForm')">提交</el-button></el-form-item></el-col></el-row></el-form></div></template><script>export default {data() {var checkMoney = (rule, value, callback) => {if (!value) {return callback(new Error('金额不能为空'));}setTimeout(() => {if (!Number.isInteger(value)) {callback(new Error('请输入数字值'));} else {if (value < 0) {callback(new Error('范围在0-255'));} else if(value > 255){callback(new Error('范围在0-255'));}else {callback();}}}, 100);};return {ruleForm: {money:'',},rules: {money:[{ validator: checkMoney, trigger: 'blur' }],}};},methods: {submitForm(formName) {this.$refs[formName].validate((valid) => {if (valid) {alert('成功');} else {return false;}});},}}</script>

效果

赞(0) 打赏
未经允许不得转载:爱站程序员基地 » Element-ui 中表单(Form)验证数字值范围(大小)