I need to implement validation for an input field that only accepts capital letters and numbers, following a specific format (AAA-111). The first 3 characters should be alphabets, followed by a hyphen, and then the last 3 characters should be numbers.
<template>
<div class="mt-6">
<input
type="text"
placeholder="XXX-XXX"
class="w-56 text-2xl bg-grat-300 p-3 rounded-lg focus:outline-none"
v-model="number_plate"
/>
<br />
</div>
</template>
<script>
export default {
props: ['template'],
data: function() {
return {
number_plate: '',
regex: '^[A-Z]{3}-d{3}'
};
},
watch: {
number_plate() {
this.number_plate = this.number_plate.match(/(^[A-Z]{3})(\d{3})/g, '$1-$2');
}
}
};
</script>
I've attempted to use a solution but encountered issues since I'm new to Vue. Any help would be appreciated.
After following a tutorial and adapting code for number validation with a specific pattern, I faced difficulties making modifications. The first input field functions correctly displaying numbers in the format 000-000, but the second one doesn't work as expected for AAA-000.
<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>