I am trying to auto-format the postal code after entry by the user. The postal code rule is Please use the format A0A 0A0 or 12345. So if the user enters L9V0C7, it auto reformats to L9V 0C7 and when the postal code includes all digits like 12345, it stays as it is. The maxlength should be 6 when the postal code has numbers and alphabets and 5 when the postal code includes only numbers. Help me fix this handlePostalCode method.
The issue I am facing is when I enter L9V0, 0 disappears and I am not able to enter the postal code any further.
<v-text-field
label='Postal Code'
class="required"
v-model='postal_code'
required
@input="handlePostalCode"
validate-on-blur
:rules='postalCodeRules'>
</v-text-field>
postalCodeRules: [
value => /^[A-z]\d[A-z] \d[A-z]\d$|^\d\d\d\d\d$/.test(value) || 'Please use the format A0A 0A0 or 12345'
]
handlePostalCode() {
if (this.postal_code.match(/^[0-9]+$/) != null) {
var replacedInput = this.postal_code.replace(/\D/g, '').match(/(\d{0,3})(\d{0,2})/);
this.postal_code = !replacedInput[2] ? replacedInput[1] : replacedInput[1] + '' + replacedInput[2];
}
else {
var replacedInput = this.postal_code.match(/(\w{0,3})(\w{0,3})/);
console.log(replacedInput)
this.postal_code = !replacedInput[2] ? replacedInput[1] : replacedInput[1] + ' ' + replacedInput[2];
}
}
[A-z]needs to be[A-Za-z]to avoid false positives. YourpostalCodeRulestest can be/^(?:[A-Za-z]\d[A-Za-z] \d[A-Za-z]\d|\d{5})$/handlePostalCodepossibly this:if (/^\d+$/.test(this.postal_code) { this.postal_code = postal_code.replace(/^(\d{5}).*$/, '$1'); } else { this.postal_code = this.postal_code.replace(/^(\w{0,3})(\w{0,3})$/, '$1 $2'); }