1

Estava tentando fazer uma validação de CPF , com uma quantidade a ser digitada igual a 11, do contrário uma mensagem apareceria e o texto seria apagado.

O prolema é como identificar a quantidade de linhas que estão sendo digitadas; já venho tentando a um tempo, como sou novo em programação não sei bem me utilizar de suas lógicas...

Segue o código:

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:Perdão pela má formatação...

2 Respostas 2

1

O melhor jeito é dentro do seu TextInput você adicionar um evento de onSubmitEditing

Exemplo:

onSubmitEditing={() => { this.checkCPF(); }}

Ou seja, o onSubmitEditing vai ser chamado quando você terminar de digitar o CPF no campo. Então você chama a função de check.

checkCPF() {
    const { cpf } = this.state;
    if (cpf.length == 11) 
        Alert.alert('Valido!!')
    else
        Alert.alert('Invalido!!')
}
1

Caso você queira definir um regex para validar o cpf, fiz um exemplo utilizando o padrão abaixo:

xxx.xxx.xxx-xx

class App extends React.Component {
state = {
  cpf: null,
  validation: ""
}

onTextChange = (e) => {
  const cpf = e.target.value;

  if(cpf.match(/[0-9]{3}\.[0-9]{3}\.[0-9]{3}-[0-9]{2}/)) {
    this.setState({cpf, validation: "Valid cpf"})
  }
  else {
    this.setState({cpf, validation: "Invalid cpf format"})
  }
}

render() {
 return (
   <div>
     <input type="text" onChange={this.onTextChange} />
     {this.state.validation ? <p>{this.state.validation}</p> : null }
   </div>
 )
}

}


ReactDOM.render(<App />, document.getElementById("app"));

Se o cpf estiver no formato definido, a mensagem de "Valid Cpf" será exibida.

1
  • Muito obrigado pela dica, esse novo modo de fazê-lo esclareceu um pouco as coisas :) 10/12/2018 às 15:46

Você deve fazer log-in para responder a esta pergunta.

Esta não é a resposta que você está procurando? Pesquise outras perguntas com a tag .