Reputation: 668
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
.
Upvotes: 13
Views: 25639
Reputation: 205
You can simply validate spaces in your onChangeText function like this
onChangeText={(text) => {
if (text.includes(' ')) {
setText(text.trim());
} else {
setText(text);
}
}
}
Upvotes: 4
Reputation: 51
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
Upvotes: 3
Reputation: 4464
This simple regex should work using .replace
function :
passwordHandle(value){
this.setState({
password: value.replace(/\s/g, '')
})
}
Upvotes: 27