forked from MapComplete/MapComplete
Refactoring: move all code files into a src directory
This commit is contained in:
parent
de99f56ca8
commit
e75d2789d2
389 changed files with 0 additions and 12 deletions
54
src/UI/InputElement/Validators/PhoneValidator.ts
Normal file
54
src/UI/InputElement/Validators/PhoneValidator.ts
Normal file
|
@ -0,0 +1,54 @@
|
|||
import { parsePhoneNumberFromString } from "libphonenumber-js"
|
||||
import { Validator } from "../Validator"
|
||||
import { Translation } from "../../i18n/Translation"
|
||||
import Translations from "../../i18n/Translations"
|
||||
|
||||
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 {
|
||||
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) {
|
||||
if (str.startsWith("tel:")) {
|
||||
str = str.substring("tel:".length)
|
||||
}
|
||||
let countryCode = undefined
|
||||
if (country) {
|
||||
countryCode = country()
|
||||
}
|
||||
return parsePhoneNumberFromString(
|
||||
str,
|
||||
countryCode?.toUpperCase() as any
|
||||
)?.formatInternational()
|
||||
}
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue