Home > Software design >  Input formatting for phone number via regex in element plus
Input formatting for phone number via regex in element plus

Time:10-24

Some help would be appreciated with tiny but very frustrating problem. I'm working on Vue project with element plus library. User input: '123456789' I need to make it: ' 998-(12) 345-67-89

Element plus have formatter, but I need to make it with Regex. Unfortunately I'm having a hard time making it work. https://element-plus.org/en-US/component/input.html#formatter

I did only checked for number now and cant figure out furthermore

<script setup>
import { ref, unref } from 'vue'
import { ElInput } from 'element-plus'

const phoneNumber = ref('')
</script>
<template>
  <el-input v-model="phoneNumber" :formatter="(value) => value.replace(/\D/g, '')" />
</template>

CodePudding user response:

You can use the following regex:

value.replace(/^\ 998|\D/g, '').replace(/^(\d{1,2})(\d{1,3})?(\d{1,2})?(\d{1,2})?.*/, (m, g1, g2, g3, g4) => ` 998-(${g1})`   (g2 ? `-${g2}` : '')   (g3 ? `-${g3}` : '')   (g4 ? `-${g4}` : '')))

The first .replace(/^\ 998|\D/g, '') removes 998 at the start of string (that was added by the successful consequent replacement) and any non-digit char, and replace(/^(\d{1,2})(\d{1,3})?(\d{1,2})?(\d{1,2})?.*/, (m, g1, g2, g3, g4) => ` 998-(${g1})` (g2 ? `-${g2}` : '') (g3 ? `-${g3}` : '') (g4 ? `-${g4}` : '')) re-formats the number by adding - only when necessart as you type.

  • Related