Vue 3 pattern for input

Viewed 87

I want to create input in which I can replace entered chars with empty chars if the pattern doesn't match.

template:

<input
  type="text"
  :value="val"
  @input="input"
/>

script:

import { ref } from "vue";
export default {
  setup() {
    let val = ref("");
    const input = ({ target }) => {
      val.value = target.value.replace(/[^\d]/g, "");
    };
    return { val, input };
  },
};

Sandbox

3 Answers

You can use watcher to remove entered numbers:

const { ref, watch } = Vue
const app = Vue.createApp({
  setup() {
    let val = ref("");
    watch(val,
      (newValue, oldValue) => {
        val.value = newValue.replace(/\d+/g, "")
      },
    );
    return { val };
  },
})
app.mount('#demo')
<script src="https://unpkg.com/vue@3/dist/vue.global.prod.js"></script>
<div id="demo">
<div>
    <input
      type="text"
      placeholder="Full Name"
      autocomplete="off"
      v-model="val"
    />
  </div>
  {{ val }}
</div>

If you want to allow the user to input only numbers, you can also do this natively in HTML with <input type="number">.

In your code you are replace content when pattern is match. and according to your question you want to make null when pattern is not match.

setup() {
    let val = ref("");
    const input = ({ target }) => {
      if (target && !target.value) val.value = "";
      if (!/[^\d]/g.test(target.value)) {
        val.value = "";
      }
      val.value = target.value;
      // val.value = target.value.replace(/[^\d]/g, "");
    };
    return { val, input };
  },

and better way is to make directive ,if you also want to implement in more input fields.

const app = createApp({})


app.directive('text-format', {
    mounted(el, binding) {
    el._listner = el.addEventListener("input", (e) => {
      if (!binding.value.test(el.value)) {
        el.value = "";
      }
    });
  },
  unmounted(el) {
    el.removeEventListener("input", el._listner);
  },
})

your input field now

 <input
      v-text-format="/[^\d]/g"
      type="text"
      placeholder="Full Name"
      autocomplete="off"
      v-model="val"
    />
Related