이 자습서에서는 React에서 사용자 이름과 암호를 확인하는 방법을 배웁니다. 이 예에서는 사용자 이름, 이메일, 비밀번호 및 비밀번호 확인 필드가 있는 간단한 양식을 만듭니다. 그런 다음 비밀번호에 대한 유효성 검사를 추가하고 다음 전체 예와 같이 비밀번호를 확인합니다.
1단계: React 앱 설치
첫 번째 단계에서 아직 설치하지 않은 경우 다음 명령을 사용하여 react js 새 앱을 다운로드해야 합니다.
npx create-react-app my-app
2단계: DemoForm 구성 요소 만들기
이 단계에서는 DemoForm.js 구성 요소 파일을 만들고 양식 유효성 검사 코드를 작성합니다. 다음과 같이 코드를 추가해 보겠습니다.
import React from 'react';
class DemoForm extends React.Component {
constructor() {
super();
this.state = {
input: {},
errors: {}
};
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleChange(event) {
let input = this.state.input;
input[event.target.name] = event.target.value;
this.setState({
input
});
}
handleSubmit(event) {
event.preventDefault();
if(this.validate()){
console.log(this.state);
let input = {};
input["username"] = "";
input["email"] = "";
input["password"] = "";
input["confirm_password"] = "";
this.setState({input:input});
alert('Demo Form is submitted');
}
}
validate(){
let input = this.state.input;
let errors = {};
let isValid = true;
if (!input["username"]) {
isValid = false;
errors["username"] = "Please enter your username.";
}
if (typeof input["username"] !== "undefined") {
const re = /^\S*$/;
if(input["username"].length < 6 || !re.test(input["username"])){
isValid = false;
errors["username"] = "Please enter valid username.";
}
}
if (!input["email"]) {
isValid = false;
errors["email"] = "Please enter your email Address.";
}
if (typeof input["email"] !== "undefined") {
var pattern = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);
if (!pattern.test(input["email"])) {
isValid = false;
errors["email"] = "Please enter valid email address.";
}
}
if (!input["password"]) {
isValid = false;
errors["password"] = "Please enter your password.";
}
if (!input["confirm_password"]) {
isValid = false;
errors["confirm_password"] = "Please enter your confirm password.";
}
if (typeof input["password"] !== "undefined") {
if(input["password"].length < 6){
isValid = false;
errors["password"] = "Please add at least 6 charachter.";
}
}
if (typeof input["password"] !== "undefined" && typeof input["confirm_password"] !== "undefined") {
if (input["password"] != input["confirm_password"]) {
isValid = false;
errors["password"] = "Passwords don't match.";
}
}
this.setState({
errors: errors
});
return isValid;
}
render() {
return (
<div>
<h1>React Username and Password Validation Example</h1>
<form onSubmit={this.handleSubmit}>
<div class="form-group">
<label for="username">Username:</label>
<input
type="text"
name="username"
value={this.state.input.username}
onChange={this.handleChange}
class="form-control"
placeholder="Enter username"
id="username" />
<div className="text-danger">{this.state.errors.username}</div>
</div>
<div class="form-group">
<label for="email">Email Address:</label>
<input
type="text"
name="email"
value={this.state.input.email}
onChange={this.handleChange}
class="form-control"
placeholder="Enter email"
id="email" />
<div className="text-danger">{this.state.errors.email}</div>
</div>
<div class="form-group">
<label for="password">Password:</label>
<input
type="password"
name="password"
value={this.state.input.password}
onChange={this.handleChange}
class="form-control"
placeholder="Enter password"
id="password" />
<div className="text-danger">{this.state.errors.password}</div>
</div>
<div class="form-group">
<label for="password">Confirm Password:</label>
<input
type="password"
name="confirm_password"
value={this.state.input.confirm_password}
onChange={this.handleChange}
class="form-control"
placeholder="Enter confirm password"
id="confirm_password" />
<div className="text-danger">{this.state.errors.confirm_password}</div>
</div>
<input type="submit" value="Submit" class="btn btn-success" />
</form>
</div>
);
}
}
export default DemoForm;
3단계: 컴포넌트 가져오기
이 단계에서는 index.js 기본 파일에서 DemoFormcomponent를 가져옵니다. index.js 파일을 다음과 같이 업데이트해 보겠습니다.
import React from 'react';
import ReactDOM from 'react-dom';
import * as serviceWorker from './serviceWorker';
import 'bootstrap/dist/css/bootstrap.min.css';
import DemoForm from './DemoForm';
ReactDOM.render(
<React.StrictMode>
<div className="container">
<DemoForm />
</div>
</React.StrictMode>,
document.getElementById('root')
);
serviceWorker.unregister();
이제 애플리케이션을 실행할 준비가 되었으므로 다음 명령을 사용하여 실행해 보겠습니다.
npm start
다음 URL을 엽니다.
http://localhost:3000
출력은 다음과 같아야 합니다.
행복한 코딩!!!