Reputation: 319
I am trying to have a user add a username upon sign up. The thing is, I do not want to allow any symbols other than underscore (_) and dash (-). I do not know how to limit the symbols allowed to just these two. Currently, my code checks for minimum length, maximum length, checks if the username is already in use, and trims the whitespace:
checkUsername = async() => {
//Check for minimum length reached
if(this.state.username.length < 3) { <-------------------------- Check for minimum length
console.log('Your text is less than what is required.');
}
else { <----------------------- Minimum length reached, now we can check database if the username already exists
await Firebase.firestore()
.collection('usernames')
.doc(this.state.username)
.get()
.then(function(doc) {
if (doc.exists) {
console.log("username in use")
} else {
console.log("username is ok");
}
}.bind(this));
}
}
render() {
return (
<View style={styles.container}>
<Text style={styles.headerText}>traderank</Text>
<TextInput
style={styles.inputBox}
value={this.state.username.trim()} <------------------- Get rid of whitespace
onChangeText={username => this.setState({ username })}
placeholder='username'
autoCapitalize='none'
maxLength={15} <-------------- make sure username does not exceed 15 characters
/>
<TouchableOpacity
style={styles.button}
onPress={this.handleSignUp}>
<Text style={styles.buttonText}>sign up</Text>
</TouchableOpacity>
<Button title="back to login"
onPress={() => this.props.navigation.navigate('Login')}/>
</View>
)
}
}
I am guessing I should add the logic to ensure only dash or underscores are involved when I check for minimum length, but have no idea how to do so. Thanks in advance.
Upvotes: 0
Views: 204
Reputation: 319
I solved the problem by adding this:
<TextInput
style={styles.inputBox}
value={this.state.username.trim().replace(/[^\w\s]/gi, "")} <-------------------
onChangeText={username => this.setState({ username })}
placeholder='username'
autoCapitalize='none'
autoCorrect={false}
maxLength={15}
/>
The replace disallows everything (special symbols) except underscores, letters and numbers. No dashes, but that's okay for now. If someone has a better solution I am all ears!
Upvotes: 1