Is it possible to implement custom input field validation using Regex? I aim to restrict the input field to three alphabets followed by three numbers, separated by a hyphen. Additionally, I want this validation to occur in real-time as the user types.
While I have found solutions for validating numbers, combining alphabet and number validation has proven challenging. Moreover, I want the input field to validate with each keystroke.
<template>
<div class="mt-6">
<input
type="text"
:placeholder="number_template"
class="w-56 text-2xl bg-grat-300 p-3 rounded-lg focus:outline-none"
v-model="number"
/>
<br /><br />
<input
type="text"
:placeholder="reg_template"
class="w-56 text-2xl bg-grat-300 p-3 rounded-lg focus:outline-none"
v-model="number_plate"
/>
</div>
</template>
<script>
export default {
props: ['number_template', 'reg_template'],
data: function() {
return {
number: '',
number_format: '', // number pattern for now XXX-XXX
regex: '', //regex for number pattern
reg_regex: '', // regex for registration plate number
reg_format: '', // pattern for registration number for now XXX-XXX (first 3 are letters and last 3 are numbers)
number_plate: ''
};
},
mounted() {
let x = 1;
this.format = this.number_template.replace(/X+/g, () => '$' + x++);
console.log(this.format);
this.number_template.match(/X+/g).forEach((char, key) => {
this.regex += '(d{' + char.length + '})?';
console.log(this.regex);
console.log(char.length);
console.log(key);
});
let y = 1;
this.reg_format = this.reg_template.replace(/X+/g, () => '$' + y++);
console.log(this.reg_format);
this.reg_template.match(/X+/g).forEach((char, key) => {
this.reg_regex += '(d{' + char.length + '})?';
console.log(this.reg_regex);
console.log(char.length);
console.log(key);
});
},
watch: {
number() {
this.number = this.number
.replace(/[^0-9]/g, '')
.replace(/^(\d{3})?(\d{3})/g, this.format)
.substr(0, this.number_template.length);
},
number_plate() {
this.number_plate = this.number_plate
.replace(/([A-Z]{3})?(d{3})/g, this.format)
.substr(0, this.reg_template.length);
}
}
};
</script>
The code successfully validates the first input field but encounters issues with the second one. There might be necessary modifications within the mounted function where the reg_regex is handled, though I am unsure of how to proceed.