search

Home  >  Q&A  >  body text

Using regular expressions to format phone number input in Element Plus

Any help with minor but very frustrating issues would be greatly appreciated. I'm developing a Vue project using element plus library. User input: '123456789' I need to dial:' 998-(12) 345-67-89

Element plus has formatter but I need to make it using regular expressions. Unfortunately I'm having trouble getting it to work. https://element-plus.org/en-US/component/input.html#formatter

I have only checked the number now and cannot learn more

<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>


P粉191323236P粉191323236334 days ago558

reply all(1)I'll reply

  • P粉235202573

    P粉2352025732023-12-31 11:45:30

    You can use the following regular expressions:

    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 the 998 at the beginning of the string (replaced by a successful follow-up) and any non Numeric characters, 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}` : '')) Start as you type only if necessary by adding -.

    reply
    0
  • Cancelreply