How to identify text size (Lenght) with a state

Asked

Viewed 232 times

1

I was trying to do a CPF validation , with a number to be typed equal to 11, otherwise a message would appear and the text would be deleted.

The prolema is like identifying the number of lines that are being typed; I’ve been trying for a while, as I’m new in programming I don’t know how to make use of their logic...

Follows 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...

2 answers

1

If you want to set a regex to validate Cpf, I made an example using the pattern below:

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"));

If Cpf is in the defined format, the "Valid Cpf" message will be displayed.

  • Thank you so much for the tip, this new way of doing it clarified things a little :)

1


The best way is inside your Textinput you add an event of onSubmitEditing

Example:

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

That is, onSubmitEditing will be called when you finish typing the CPF into the field. Then you call the check function.

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.