问题描述
我希望用户在单击“提交”按钮时避免添加空格。我在手柄更改中显示警报消息,因此,如果用户添加空格,它将显示。
但是我想在handlesubmit中显示警报消息。
下面是我的代码:
handleChange(event) {
let reWhiteSpace = new RegExp(/\s/);
var errors = {}
if (event.target.id === 'userID') {
this.setState({ userID: event.target.value })
errors.userID = reWhiteSpace.test(event.target.value)
if (errors.userID) {
this.setState({
alertMessage: "Spacing Not Allowed",showAlert: true,alertcolor: "warning"
})
}
}
this.setState({
errors: errors
})
}
handleSubmit(event) {
event.preventDefault();
console.log('form submission data',this.state);
var data = this.state;
if (this.state.userID !== '' ) {
const requestOptions = {
method: 'POST',headers: new Headers({
'Content-Type': 'application/json','Access-Control-Allow-Origin': '*'
}),body: JSON.stringify(data)
};
console.log(requestOptions)
fetch(API_URL,requestOptions)
.then(res => res.json())
.then((data) => {
console.log(data)
if (data.status) {
window.location = '/user-list'
if (data.message !== "") {
this.setState({
alertMessage: data.message,alertcolor: "success"
})
}
}
else if (data.message !== "") {
console.log('else',data.message)
this.setState({
alertMessage: data.message,alertcolor: "warning"
})
}
})
.catch(console.log)
}
else {
this.setState({
alertMessage: "Please enter all required fields",alertcolor: "warning"
})
}
}
我想检查句柄提交中的空白验证 有什么建议吗?
解决方法
由于您将errors
储存在状态中,因此您也可以在handleSubmit
中对其进行检查:
handleSubmit(event) {
event.preventDefault();
if (this.state.errors && this.state.errors.userID) {
this.setState({
alertMessage: "Please enter all required fields",showAlert: true,alertcolor: "warning"
})
return;
}
console.log('form submission data',this.state);
var data = this.state;
if (this.state.userID !== '' ) {
const requestOptions = {
method: 'POST',headers: new Headers({
'Content-Type': 'application/json','Access-Control-Allow-Origin': '*'
}),body: JSON.stringify(data)
};
console.log(requestOptions)
fetch(API_URL,requestOptions)
.then(res => res.json())
.then((data) => {
console.log(data)
if (data.status) {
window.location = '/user-list'
if (data.message !== "") {
this.setState({
alertMessage: data.message,alertcolor: "success"
})
}
}
else if (data.message !== "") {
console.log('else',data.message)
this.setState({
alertMessage: data.message,alertcolor: "warning"
})
}
})
.catch(console.log)
}
else {
this.setState({
alertMessage: "Please enter all required fields",alertcolor: "warning"
})
}
}
如果只想在字符串的开头/结尾检查空格,则可以使用trim()
方法而不是正则表达式:
function checkWhiteSpace(text) {
const _text = text.trim();
return text === _text;
}
您还可以避免所有这些空白验证,而可以通过编程方式将其删除,然后再使用string.trim()
方法发送请求。您可以read more here