rajansu
rajansu

Reputation: 33

How to create an input field mask in Vue3 using regex for vehicle registration number?

How to create an input field mask in Vue3 using regex for vehicle registration number? I found the solution for masking telephone numbers but when I mix the regex with alphabets it doesn't work at all.

Is it possible to create a mask for something like AAA-000 i.e. first three inputs as alphabets and the last three as numbers separated by '-'?

Answer:

Daniel's answer worked like the charm in my case. Just if anyone is searching for the same here is the link : https://github.com/beholdr/maska

Upvotes: 3

Views: 11924

Answers (1)

Daniel
Daniel

Reputation: 35714

There's quite a bit more to field validation than just making sure the regex works. For good UX experience, you need to make sure the user can edit any character in the input field, delete a character and paste values into it. That's why it is handy to just use an implementation that already has all that available.

The library I've used in the past is maska which is Vue3 compatible.

It allows you to create a field using a replacement mask

tokens = {
    '#': { pattern: /[0-9]/ },
    'X': { pattern: /[0-9a-zA-Z]/ },
    'S': { pattern: /[a-zA-Z]/ },
    'A': { pattern: /[a-zA-Z]/, uppercase: true },
    'a': { pattern: /[a-zA-Z]/, lowercase: true },
    '!': { escape: true },
    '*': { repeat: true }
}

if those are not enough, it allows you to define additional tokens

but those should be enough to get what you need

<input data-mask='AAA-###'>

Upvotes: 5

Related Questions