PhoneInput.vue 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. <template>
  2. <v-text-field
  3. :model-value="modelValue"
  4. :rules="[validateRequired, validatePhone]"
  5. :label="label"
  6. :required="required"
  7. type="tel"
  8. @update:model-value="updateValue"
  9. />
  10. </template>
  11. <script setup lang="ts">
  12. import { isValidPhoneNumber } from 'libphonenumber-js'
  13. const props = defineProps({
  14. modelValue: {
  15. type: String,
  16. default: '',
  17. },
  18. label: {
  19. type: String,
  20. default: 'Téléphone',
  21. },
  22. required: {
  23. type: Boolean,
  24. default: false,
  25. },
  26. countryCode: {
  27. type: String,
  28. default: 'FR',
  29. },
  30. })
  31. const emit = defineEmits(['update:modelValue'])
  32. const updateValue = (value: string) => {
  33. emit('update:modelValue', value)
  34. }
  35. // Validation rules
  36. const validateRequired = (value: string) =>
  37. !props.required || !!value || 'Ce champ est obligatoire'
  38. const validatePhone = (phone: string) => {
  39. if (!phone) return true
  40. try {
  41. // Use the provided country code or default to FR
  42. return (
  43. isValidPhoneNumber(phone, props.countryCode) ||
  44. 'Numéro de téléphone invalide'
  45. )
  46. } catch (error) {
  47. return 'Numéro de téléphone invalide'
  48. }
  49. }
  50. </script>