How can I enforce a specific sequence for user input, restricting the first two characters to alphabets, the next two to numbers, the following two to characters, and the last four to numbers? I need to maintain the correct format of an Indian vehicle registration number without allowing incorrect entries. An example of the desired output is:
HR 23 DU 2323
vehicleNumberFormat() {
const { value } = this.myForm.get('vehicleNumber');
console.log('value', value);
const regex = /^(\w{0,2})(\w{0,2})(\w{0,2})(\w{0,4})$/g
// const onlyNumbers = value.replace(/[^\d]/g, '')
const typedValue = value.replace(/[^\w]/g, '')
const formatedVehicleNumber = typedValue.replace(regex, (regex, $1, $2, $3, $4) =>
[$1, $2, $3, $4].filter(group => !!group).join(' ')
)
console.log('formatedVehicleNumber-->', formatedVehicleNumber.toUpperCase())
this.myForm.controls['vehicleNumber']?.setValue(formatedVehicleNumber.toUpperCase());
return formatedVehicleNumber;
}
Check out the codebase on StackBlitz