I was trying to do a CPF validation, with a quantity to be entered equal to 11, otherwise a message would appear and the text would be erased.
The problem is how to identify the number of lines being typed; I have been trying for a while, as I am new to programming I do not know how to use my logic ...
Follow the code:
import React from 'react'
import { StyleSheet, View,Alert,Button } from 'react-native'
import { TextInputMask } from 'react-native-masked-text'
import { Kaede } from 'react-native-textinput-effects'
export default class App extends React.Component {
constructor(props) {
super(props)
this.state = {
cpf: '',
myNumber:'',
myValid:''
}
}
onChange(text) {
let newText = '';
let numbers = '0123456789';
for (var i = 0; i < text.length; i++) {
if ( numbers.indexOf(text[i]) > -1 ) {
newText = newText + text[i];
}
}
this.setState({myNumber: newText})
}
onPress(text){
let newText = '';
if( this.state.cpf.length == 11){
Alert.alert('Valido!!')
} else {
Alert.alert('inválido...')
this.setState({myNumber:newText})
}
}
render() {
return (
<View style={styles.container}>
<TextInputMask
refInput={(ref) => this.myDateText = ref }
// here we set the custom component and their props.
customTextInput={Kaede}
customTextInputProps={{
style:{ width: '80%' },
label:'CPF'
}}
maxLength={14}
type={'datetime'}
options={{
format: '999.999.999-99'
}}
onChangeText={ cpf => this.setState({ cpf }),(text)=> this.onChange(text) }
value={this.state.cpf,this.state.myNumber,this.state.myValid}
/>
<Button
onPress={(text)=> this.onPress(text)}
title="Validar"
color="#841584"
/>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'center'
}
})
PS: Sorry for the bad formatting ...