Reputation: 1
I am completely new to react-native and have been trying to custom mask input. However, I am only getting numbers more than 10 even if I have specified the mask under TextInput. I am not sure what I am doing wrong. Your assistance will be greatly appreciated.
Please see my code below:
import React, { Component } from "react";
import { StyleSheet, SafeAreaView, TextInput } from "react-native";
export default class InputMask extends Component {
state = {
mask: '',
}
customMask = (mask) => {
if ( typeof mask == 'String') {
for (let i = 0; i < mask.length; i++) {
if ( mask == '9') {
return mask.replace(/[^0-9]+/g, '')
}
if ( mask == 'a') {
return mask.replace(/[^a-zA-Z]+/g, '')
}
if ( mask == 's') {
return mask.replace(/[^a-zA-Z0-9]+/g, '')
}
if ( mask == '*') {
return mask
}
}
}
this.setState({
mask: mask.substring(0, mask.length) || ''
})
}
render() {
return (
<SafeAreaView style={styles.container}>
<TextInput
mask= '(999) 999 9999'
placeholder="Enter phone number"
value={this.state.mask}
onChangeText={this.customMask}
style={styles.input}
keyboardType="phone-pad"
/>
</SafeAreaView>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: "center",
},
input: {
height: 40,
margin: 12,
borderWidth: 1,
padding: 10,
},
});
Upvotes: 0
Views: 10476
Reputation: 97
customMask = (text) => {
let newText = '';
let mask = '(999) 999 9999';
for (let i = 0, j = 0; i < text.length; i++) {
if (mask[j] === '9') {
if (/\d/.test(text[i])) {
newText += text[i];
j++;
}
} else {
newText += mask[j];
j++;
}
}
this.setState({ mask: newText });
};
Explanation of Changes:
Function argument: The function now takes text as an argument, which is the input value from the TextInput.
Iterating over text: The function iterates over each character of the input text.
Matching mask characters: It compares the current position in the mask with the character '9'.
Appending characters: If the mask character is '9', it appends the input character to newText only if it's a digit. Otherwise, it appends the mask character to newText.
Updating state: Finally, the updated newText is set to the state's mask property.
Upvotes: 0
Reputation: 451
Firstly seems like the mask props you are trying to pass to RN TextInput are not available you can look through here to see available props. Secondly, seems like the way you are approaching is not the way you want to proceed I recommend you understand how and what the props for text input give and do then start creating a custom component. For your masked input you can external libraries like this (not promoting just an example) as they exist to make our lives easier but if you are still keen on making custom components you can browse through their GitHub repo and see on how they have implemented it and try something similar like this.
Upvotes: 0