Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

panthro's avatar

How to add a leading zero?

How can I add a leading zero to a text input?

const day = ref('');

<input type="text" v-model="day" />

So, I've tried a watcher:

watch(day, (newValue) => {
    day.value = newValue.toString().padStart(2, '0');
});

This works, but if I type, 1 it turns into 01 as expected but if I highlight the input and hit 1 again, it is not transformed with the leading zero.

Is there anyway to make this work?

0 likes
1 reply
Smash's avatar

There's a cool way to handle this sort of thing!

But first off, when you need to mutate a reactive input value in Vue, it's generally a good idea to not use our reactive ref() value with 2-way binding (ie the v-model approach).

Instead, we can use the input's more traditional value attribute to output the reactive ref's value to the user's input/view (ie "1 way"). This allows us to now catch any changes to our ref's value via an @input event, which lets us process our reactive ref's value however we may need without 2-way binding getting in our way.

This way after processing, the ref value's changes are shown to the user via Vue's reactivity as the new (mutated) value.

Now the cool part!

We can use a Number() method to automatically drop the leading zeroes by wrapping the input's target.value with it. So as the value is manipulated through the pipe, leading zero's get added back in as needed, but now the leading zero stops showing up past the .padStart() method's 1st argument's threshold.

const day = ref('')

// With Typescript
// NOTE: this is a one liner without Typescript (see 2nd input example below)
const padInputValue = (event:Event) => {
    const target = event.target as HTMLInputElement
    day.value = Number(target.value).toString().padStart( 2, '0' )
}
<template>

    <!-- With Typescript -->
    <input
        type="number"
        inputmode="numeric"
        pattern="[0-9]"
        min="1"
        max="31"
        step="1"
        :value="day"
        @input="padInputValue($event)"
    />

    <!-- Without Typescript -->
    <input
        type="number"
        inputmode="numeric"
        pattern="[0-9]"
        min="1"
        max="31"
        step="1"
        :value="day"
        @input="day = Number($event.target.value).toString().padStart(2, '0')"
    />

</template>

Please or to participate in this conversation.