Reputation: 2659
i want the phone number(work Phone) format to be as shown in the below image, using react-native,can any one help how to work out it,any help much appreciated
Upvotes: 6
Views: 17835
Reputation: 364
This is a slightly more involved solution, but it:
(55
or 5 digits as (555) 55
, or 6 as (555) 555-
)function formatPhoneNumber (text, previousText) {
if (!text) return text
const deleting = previousText && previousText.length > text.length
if (deleting) {
return text
}
let cleaned = text.replace(/\D/g, '') // remove non-digit characters
let match = null
if (cleaned.length > 0 && cleaned.length < 2) {
return `(${cleaned}`
} else if (cleaned.length == 3) {
return `(${cleaned}) `
} else if (cleaned.length > 3 && cleaned.length < 5) {
match = cleaned.match(/(\d{3})(\d{1,3})$/)
if (match) {
return `(${match[1]}) ${match[2]}`
}
} else if (cleaned.length == 6) {
match = cleaned.match(/(\d{3})(\d{3})$/)
if (match) {
return `(${match[1]}) ${match[2]}-`
}
} else if (cleaned.length > 6) {
match = cleaned.match(/(\d{3})(\d{3})(\d{4})$/)
if (match) {
return `(${match[1]}) ${match[2]}-${match[3]}`
}
}
return text
}
Upvotes: 2
Reputation: 231
You can achieve this with regular expressions... This will format like (555) 222-9999
onTextChange(text) {
var cleaned = ('' + text).replace(/\D/g, '')
var match = cleaned.match(/^(1|)?(\d{3})(\d{3})(\d{4})$/)
if (match) {
var intlCode = (match[1] ? '+1 ' : ''),
number = [intlCode, '(', match[2], ') ', match[3], '-', match[4]].join('');
this.setState({
phoneNum: number
});
return;
}
this.setState({
phoneNum: text
});
}
Then on the <TextInput>
...
<TextInput
onChangeText={(text) => this.onTextChange(text) }
value={this.state.phoneNum}
textContentType='telephoneNumber'
dataDetectorTypes='phoneNumber'
keyboardType='phone-pad'
maxLength={14}
/>
Upvotes: 12