mapcomplete/UI/InputElement/Validators/PhoneValidator.ts

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

55 lines
1.6 KiB
TypeScript
Raw Normal View History

import { parsePhoneNumberFromString } from "libphonenumber-js"
import { Validator } from "../Validator"
import { Translation } from "../../i18n/Translation"
import Translations from "../../i18n/Translations"
2023-03-29 17:21:20 +02:00
export default class PhoneValidator extends Validator {
constructor() {
super("phone", "A phone number", "tel")
}
getFeedback(s: string, requestCountry?: () => string): Translation {
if (this.isValid(s, requestCountry)) {
return undefined
}
const tr = Translations.t.validation.phone
const generic = tr.feedback
if (requestCountry) {
const country = requestCountry()
if (country) {
return tr.feedbackCountry.Subs({ country })
}
}
return generic
}
public isValid(str, country: () => string): boolean {
2023-03-29 17:21:20 +02:00
if (str === undefined) {
return false
}
if (str.startsWith("tel:")) {
str = str.substring("tel:".length)
}
let countryCode = undefined
if (country !== undefined) {
countryCode = country()?.toUpperCase()
}
return parsePhoneNumberFromString(str, countryCode)?.isValid() ?? false
}
public reformat(str, country: () => string) {
2023-03-29 17:21:20 +02:00
if (str.startsWith("tel:")) {
str = str.substring("tel:".length)
}
let countryCode = undefined
if (country) {
countryCode = country()
}
2023-03-29 17:21:20 +02:00
return parsePhoneNumberFromString(
str,
countryCode?.toUpperCase() as any
2023-03-29 17:21:20 +02:00
)?.formatInternational()
}
}