React.JS验证两个输入



我目前正在学习React JS。我有一个允许用户注册的注册文件。在将信息传递到该注册文件中的服务器之前,我想验证这两个字段是否相互匹配。我的代码如下图所示。我做了一些搜索,注意到一个基本的术语叫做"handlechange"。被扔来扔去,但我不知道如何使用我的"onchange"。事件。如有任何建议,我将不胜感激。

import React, { useState } from 'react';
import Axios from 'axios';
import './Register.css';
function Register() {
const [firstName, setFirstName] = useState('');
const [lastName, setLastName] = useState('');
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const register = () => { 
Axios.post('http://localhost:3001/user/register', {
firstName: firstName,
lastName: lastName,
email: email,
password: password
}).then((response) => {
console.log(response);
});
};
return (
<div className='Register'>
<h1>Registration</h1>
<div className='RegisterForm'>
<input type='text' name='firstName' placeholder='First Name' onChange={(event) => {setFirstName(event.target.value); }} />
<input type='text' name='lastName' placeholder='Last Name' onChange={(event) => {setLastName(event.target.value); }} />
</div>
<div className='RegisterForm'>
<input type='text' name='email' placeholder='Email'/>
<input type='text' name='emailConfirmation' placeholder='Confirm Email' onChange={(event) => {setEmail(event.target.value); }} />
</div>
<div className='RegisterForm'>
<input type='password' name='password' placeholder='Password'/>
<input type='password' name='passwordConfirmation' placeholder='Confirm Password' onChange={(event) => {setPassword(event.target.value); }} />
</div>
<div className='RegisterForm'>
<button onClick={register}>Register</button>
</div>
</div>
)
}
export default Register;

如果你想验证字段,那么就在axios调用之前,比较所需的字段/值,如果它们匹配,则调用axios api,否则就抛出需要在UI上显示的错误。

//Add validation inside the function
const register = () => { 
// check if firstName and LastName is not empty 
// or any other validation you want - add it here.
if(firstName === "" || LastName ===""){ 
// alert the user for invalid values
alert(" FirstName and LastName cannot be empty");
}
else  {
Axios.post('http://localhost:3001/user/register', {
firstName: firstName,
lastName: lastName,
email: email,
password: password
}).then((response) => {
console.log(response);
});
}
};

最新更新