我有下面的代码,我的麻烦是当我想检查用户是否在前面使用startsWith()
函数输入了一个数字时,我得到一个“TypeError:usernameField.startsWith is not a function”。如何防止用户输入以数字开头的用户名,但只允许在字母字符后使用数字,这样当他们将数字放在前面时,它会一目了然,然后什么都没有?
import React, { Component } from "react";
import SignupForm from "./components/SignupForm";
class App extends Component {
constructor() {
super();
this.state = {
username: "",
};
this.changeValue = this.changeValue.bind(this);
this.removeNumbers = this.removeNumbers.bind(this);
}
changeValue(event) {
this.setState({
[event.target.name]: event.target.value,
});
}
removeNumbers(usernameField) {
let numbers = /[0-9]/gi;
if (usernameField.startsWith(numbers)) {
usernameField.target.value = usernameField.target.value.replace(numbers, "");
}
}
render() {
return (
<div className="App">
<SignupForm
changeValueHandler={this.changeValue}
usernameValue={this.state.username}
usernameCharacterFilter={this.removeNumbers}
/>
</div>
);
}
}
export default App;
import React from "react";
export default function SignupForm(props) {
return (
<div className="container">
<h1>Signup Form</h1>
<div className="form-div">
<form>
<input
name="username"
type="text"
placeholder="Username"
onChange={props.changeValueHandler}
onKeyUp = {props.usernameCharacterFilter}
value={props.usernameValue}
/>
</form>
</div>
</div>
);
}