khalifathul
khalifathul

Reputation: 668

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.

Upvotes: 13

Views: 25639

Answers (3)

amit.s19
amit.s19

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

Gargantulakon
Gargantulakon

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

Dyo
Dyo

Reputation: 4464

This simple regex should work using .replace function :

passwordHandle(value){
   this.setState({
       password: value.replace(/\s/g, '')
   })
}

Upvotes: 27

Related Questions