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
.
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.
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.
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 .
This simple regex should work using .replace
function :
passwordHandle(value){
this.setState({
password: value.replace(/\s/g, '')
})
}
You can simply validate spaces in your onChangeText function like this
onChangeText={(text) => {
if (text.includes(' ')) {
setText(text.trim());
} else {
setText(text);
}
}
}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With