Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to stop entering whitespace in textInput React Native?

How to stop entering whitespace in password input field in React Native?

password might be any characters including space.

I tried this: validator.js

const extract = (str, pattern) => (str.match(pattern) || []).pop() || '';

export function removeWhiteSpace(str) {
  return extract(str, '/^\S*$/;');
}

login.js

passwordHandle(value){
  this.setState({
      password:removeWhiteSpace(value)
  })
  console.log(removeWhiteSpace(value))
}

render()

<View style={{paddingBottom:25}}>
  <TextField 
    label='Password'
    type='password' 
    value={password}
    error={errors.password}
    icon
    onChange={this.passwordHandle}/>
  <Image 
    source={require('../../../assets/img/lock.png')}
    style={styles.icon} />
</View>

But it doesn't work. It only executes the '/^\S*$/;' from removeWhiteSpace.

like image 279
khalifathul Avatar asked Feb 14 '18 11:02

khalifathul


People also ask

How do you avoid space in TextInput react native?

To remove extra space below the TextInput in the KeyboardAvoidingView with React Native, we shoule make KeyboardAvoidingView a child of ScrollView . to wrap the ScrollView around the KeyboardAvoidingView to remove extra space below the TextInput s.

How do I disable editing in TextInput react native?

To disable options on React Native TextInput, we can set the editable and selectTextOnFocus props to false . to set them both to false . Then we won't see any popup options displayed when we focus on the text input. editable set to false disables typing in the input.

How do I clear TextInput in react native?

To clear React Native TextInput, we can set the value with a state and clear the state. to set the value prop to val . And we set onChangeText to setVal to set val to the inputted value. Next, we add a Button with the onPress prop set to a function that set val to an empty string with setVal .


3 Answers

This simple regex should work using .replace function :

passwordHandle(value){
   this.setState({
       password: value.replace(/\s/g, '')
   })
}
like image 190
Dyo Avatar answered Oct 19 '22 17:10

Dyo


You can simply validate spaces in your onChangeText function like this

onChangeText={(text) => {
 if (text.includes(' ')) {
   setText(text.trim()); 
  } else {
   setText(text);
  }
 }
}
like image 44
amit.s19 Avatar answered Oct 19 '22 19:10

amit.s19


You can also use trim() from the prototype String object instead if you only care about spaces being entered at the end (or front) of the string.

passwordHandle(value){
   this.setState({
       password: value.trim()
   })
}

More info about trim(): https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/Trim

like image 43
Gargantulakon Avatar answered Oct 19 '22 18:10

Gargantulakon