Element UI provides several validation approaches, yet each prseents limitations. For instance:
-
Using
type='number'allows invalid inputs like 1-1-1. -
The
el-input-numbercomponent permits multiple decimal points. -
Regular expressions such as:
<el-input v-model='form.number' @input="(v)=>form.number=v.replace(/[^�-9.]/g,'')" />
still permit multiple decimal points.
- Custom methods also fall short of fully addressing the requirements.
To address these issues, a custom handler was developed:
<el-input
placeholder="Enter area"
v-model="form.number"
@input="handleEdit('form','number')"
style="width: 85%;margin-right: 5px;"
></el-input>
<script>
handleEdit(val1, val2) {
let value = this[val1][val2];
// Remove all non-numeric characters except decimal point
value = value.replace(/[^�-9.]/g, "");
// Prevent leading decimal point
value = value.replace(/^�/g, "");
// Limit to single decimal point
value = value.replace(/\.{2,}/g, ".");
// Ensure only one decimal point exists
value = value
.replace(".", "$#$")
.replace(/\./g, "")
.replace("$#$", ".");
this[val1][val2] = value;
},
</script>
However, this appproach still fails to prevent special characters such as '-', 'e', etc. A more effective solution involves intercepting keyboard events during input:
<el-input
type="number"
v-model="form.payFee"
@keydown.native="dealInput"
style="width: 300px;margin-right: 5px;"
></el-input> yuan
<script>
dealInput(e) {
const key = e.key;
if (key === "e" || key === "E" || key === "+" || key === "-") {
e.returnValue = false;
return false;
}
return true;
},
</script>
Complementing this with CSS styling:
input::-webkit-outer-spin-button,
input::-webkit-inner-spin-button {
-webkit-appearance: none !important;
margin: 0;
}