CODE VN

Cách xác thực số điện thoại trong React

Trong hướng dẫn này, chúng ta sẽ tìm hiểu cách xác thực số điện thoại trong React. Hướng dẫn này chúng tôi sẽ cung cấp cho bạn hướng dẫn từng bước về cách thêm xác thực số điện thoại trong ứng dụng js phản ứng. trong ví dụ này, chúng tôi sẽ lấy đầu vào tên, email, điện thoại và nhận xét và thêm xác thực cho yêu cầu, email và điện thoại 10 chữ số ngay bây giờ. cũng hiển thị thông báo lỗi nếu họ nhập giá trị sai.

  • Bước 1: Cài đặt ứng dụng React
  • Bước 2: Tạo Thành phần DemoForm
  • Bước 3: Nhập thành phần

Bước 1: Cài đặt ứng dụng React

Trước tiên cần cài đặt ứng dụng React, sử dụng lệnh bên dưới

npx create-react-app my-app

Bước 2: Tạo Thành phần DemoForm

Trong bước này, chúng tôi sẽ tạo tệp thành phần DemoForm.js và chúng tôi sẽ viết mã xác thực biểu mẫu. vì vậy hãy thêm mã như dưới đây:

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["name"] = "";
        input["email"] = "";
        input["phone"] = "";
        input["comment"] = "";
        this.setState({input:input});
  
        alert('Demo Form is submited');
    }
  }
  validate(){
      let input = this.state.input;
      let errors = {};
      let isValid = true;
  
      if (!input["name"]) {
        isValid = false;
        errors["name"] = "Please enter your name.";
      }
  
      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["phone"]) {
        isValid = false;
        errors["phone"] = "Please enter your phone number.";
      }
  
      if (typeof input["phone"] !== "undefined") {
          
        var pattern = new RegExp(/^[0-9\b]+$/);
        if (!pattern.test(input["phone"])) {
          isValid = false;
          errors["phone"] = "Please enter only number.";
        }else if(input["phone"].length != 10){
          isValid = false;
          errors["phone"] = "Please enter valid phone number.";
        }
      }
  
      if (!input["comment"]) {
        isValid = false;
        errors["comment"] = "Please enter your comment.";
      }
  
      this.setState({
        errors: errors
      });
  
      return isValid;
  }
     
  render() {
    return (
      <div>
        <h1>React Validation For Phone Number Example</h1>
        <form onSubmit={this.handleSubmit}>
  
          <div class="form-group">
            <label for="name">Name:</label>
            <input 
              type="text" 
              name="name" 
              value={this.state.input.name}
              onChange={this.handleChange}
              class="form-control" 
              placeholder="Enter name" 
              id="name" />
  
              <div className="text-danger">{this.state.errors.name}</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="Phone">Phone:</label>
            <input 
              type="text" 
              name="phone" 
              value={this.state.input.phone}
              onChange={this.handleChange}
              class="form-control" 
              placeholder="Enter phone" 
              id="email" />
  
              <div className="text-danger">{this.state.errors.phone}</div>
          </div>
  
          <div class="form-group">
            <label for="comment">Comment:</label>
            <textarea 
              name="comment"
              value={this.state.input.comment} 
              onChange={this.handleChange}
              placeholder="Enter comment"
              class="form-control" />
  
              <div className="text-danger">{this.state.errors.comment}</div>
          </div>
              
          <input type="submit" value="Submit" class="btn btn-success" />
        </form>
      </div>
    );
  }
}
  
export default DemoForm;

Bước 3: Nhập thành phần

Trong bước này, chúng tôi sẽ nhập DemoFormcomponent trong tệp chính index.js. Vì vậy, hãy cập nhật tệp index.js như sau:

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();

Bây giờ chúng tôi đã sẵn sàng để chạy ứng dụng của mình, vì vậy hãy chạy bằng lệnh dưới đây:

npm start

Mở url dưới đây:

http://localhost:3000

đầu ra

Mã hóa vui vẻ !!!

1.05 GEEK