Xác thực mật khẩu javascript

Sau khi ứng dụng được bắt đầu và được đồng bộ với mã. Khi có bất kỳ sự thay đổi bất kỳ nào của mã, sẽ được đồng bộ ngay lập tức

Màn hình hiển thị trên trình duyệt

Xây dựng các thành phần

Viết biểu mẫu với 3 đầu vào chính họ tên, email và mật khẩu. Và tạo thông báo cho từng loại đầu vào riêng. Trong phần này, bạn tạo các thành phần trong React

  • create-react-app react-password-strength
    
    8 – Bao bọc trường nhập biểu mẫu bằng các thuộc tính của nó và thay đổi trình xử lý sự kiện
  • create-react-app react-password-strength
    
    9 – Bao bọc email 
    create-react-app react-password-strength
    
    8 và thêm logic xác thực email vào đó
  • yarn add zxcvbn isemail prop-types node-sass bootstrap
    
    1 – Bao bọc mật khẩu 
    create-react-app react-password-strength
    
    8 và thêm logic xác thực mật khẩu vào đó. Cũng đính kèm đồng hồ đo độ mạnh mật khẩu và một số dấu hiệu trực quan khác vào trường
  • yarn add zxcvbn isemail prop-types node-sass bootstrap
    
    3 – Biểu mẫu Tham gia nhóm hỗ trợ hư cấu chứa các trường của biểu mẫu

Tạo thư mục ________ 34 bên trong thư mục nguồn của ứng dụng để chứa tất cả các thành phần

Thành phần FormField

Tạo tệp

yarn add zxcvbn isemail prop-types node-sass bootstrap
5 trong 
yarn add zxcvbn isemail prop-types node-sass bootstrap
6 và thêm đoạn mã sau

import React, { Component, Fragment } from 'react';
import PropTypes from 'prop-types';
class FormField extends Component {
  // initialize state
  state = { value: '', dirty: false, errors: [] }
  hasChanged = e => {
    e.preventDefault[];
    // destructure props - assign default dummy functions to validator and onStateChanged props
    const { label, required = false, validator = f => f, onStateChanged = f => f } = this.props;
    const value = e.target.value;
    const isEmpty = value.length === 0;
    const requiredMissing = this.state.dirty && required && isEmpty;
    let errors = [];
    if [requiredMissing] {
      // if required and is empty, add required error to state
      errors = [ ...errors, `${label} is required` ];
    } else if ['function' === typeof validator] {
      try {
        validator[value];
      } catch [e] {
        // if validator throws error, add validation error to state
        errors = [ ...errors, e.message ];
      }
    }
    // update state and call the onStateChanged callback fn after the update
    // dirty is only changed to true and remains true on and after the first state update
    this.setState[[{ dirty = false }] => [{ value, errors, dirty: !dirty || dirty }], [] => onStateChanged[this.state]];
  }
  render[] {
    const { value, dirty, errors } = this.state;
    const { type, label, fieldId, placeholder, children } = this.props;
    const hasErrors = errors.length > 0;
    const controlClass = ['form-control', dirty ? hasErrors ? 'is-invalid' : 'is-valid' : '' ].join[' '].trim[];
    return [
      
        
{label} {/** Render the first error if there are any errors **/} { hasErrors &&
{ errors[0] }
}
{/** Render the children nodes passed to component **/} {children}
]; } } FormField.propTypes = { type: PropTypes.oneOf[["text", "password"]].isRequired, label: PropTypes.string.isRequired, fieldId: PropTypes.string.isRequired, placeholder: PropTypes.string.isRequired, required: PropTypes.bool, children: PropTypes.node, validator: PropTypes.func, onStateChanged: PropTypes.func }; export default FormField;

Trạng thái đầu vào. Trước đó, bạn đã khởi tạo

yarn add zxcvbn isemail prop-types node-sass bootstrap
7 cho thành phần trường để theo dõi giá trị hiện tại của đầu vào, trạng thái
yarn add zxcvbn isemail prop-types node-sass bootstrap
8 và mọi lỗi hiện có

Xử lý thay đổi đầu vào. Tiếp theo, bạn đã thêm trình xử lý sự kiện hasChanged [e] để cập nhật giá trị trạng thái thành giá trị đầu vào hiện tại trên mỗi thay đổi đối với đầu vào React

Kết xuất và đạo cụ. Ở đây bạn đang hiển thị dữ liệu nhập và nhãn của nó. You also have ađiều kiện đưa ra lỗi đầu tiên trong trạng thái lỗi [nếu có bất kỳ lỗi nào]

Thành phần EmailField

Tạo tệp

yarn add zxcvbn isemail prop-types node-sass bootstrap
9 trong thư mục 
yarn add zxcvbn isemail prop-types node-sass bootstrap
6và thêm đoạn mã sau

create-react-app react-password-strength
4

Trong thành phần 

create-react-app react-password-strength
9 , bạn đang kết xuất thành phần
create-react-app react-password-strength
8 và truyền hàm xác thực email tới prop 
create-react-app react-password-strength
73. Bạn sử dụng 
create-react-app react-password-strength
74của gói
create-react-app react-password-strength
4 để xác thực email

Thành phần PasswordField

Tạo tệp 

create-react-app react-password-strength
76 trong thư mục 
yarn add zxcvbn isemail prop-types node-sass bootstrap
6và thêm đoạn mã sau

create-react-app react-password-strength
2

Thành phần này đang sử dụng gói

create-react-app react-password-strength
3 để ước tính độ mạnh của mật khẩu. Gói có zxcvbn[] lấy chuỗi mật khẩu làm đối số đầu tiên của nó và trả về một đối tượng có số thuộc tính để ước tính cường độ mật khẩu

Đây là những gì đang xảy ra trong thành phần PasswordField

Khởi tạo. Trong constructor[], bạn đã tạo hai thuộc tính,

create-react-app react-password-strength
79 và minStrength, từ chỗ dựa tương ứng của chúng được truyền cho thành phần.
create-react-app react-password-strength
50là độ dài mật khẩu tối thiểu trước khi nó có thể được coi là đủ dài. Default is 7.
create-react-app react-password-strength
51là điểm thấp nhất
create-react-app react-password-strength
3 trước khi mật khẩu được coi là đủ mạnh. Giá trị của nó nằm trong khoảng từ 0-4. Nó mặc định là 3 nếu không được tùy chỉnh

Xử lý thay đổi mật khẩu. Mật khẩu xác thực chức năng mà bạn đã xác định sẽ được chuyển đến trình xác thực prop của thành phần FormField bên dưới. Hàm đảm bảo rằng độ dài mật khẩu dài hơn

create-react-app react-password-strength
50 và cũng có điểm zxcvbn[] tối thiểu được chỉ định

Kết xuất và Đạo cụ. Tại đây, bạn đã kết xuất thành phần FormField bên dưới cùng với một số thành phần để nhập vào, máy đo mật khẩu và bộ đếm độ dài mật khẩu

Đồng hồ đo cường độ mật khẩu để biết cường độ của mật khẩu hiện tại dựa trên trạng thái và được định cấu hình ở chế độ ẩn dưới dạng động nếu độ dài mật khẩu là 0. Đồng hồ sẽ chỉ ra các màu khác nhau cho các cường độ khác nhau

Thành phần PasswordField chấp nhận hai trường,

create-react-app react-password-strength
51 và ngưỡngĐộ dài, như được định nghĩa trong propTypes của thành phần

Thành phần tham gia

Tạo tệp 

create-react-app react-password-strength
55 trong thư mục 
yarn add zxcvbn isemail prop-types node-sass bootstrap
6

yarn add zxcvbn isemail prop-types node-sass bootstrap
2

Component JoinForm bao bọc các thành phần trường form tạo nên form. Chúng ta đã khởi tạo trạng thái để giữ tính hợp lệ của ba trường. họ tên, email và mật khẩu. Tất cả đều sai hoặc không hợp lệ

Cuối cùng, biểu mẫu được kết xuất. Lưu ý rằng bạn đã thêm chức năng xác thực vào trường

create-react-app react-password-strength
57  để chắc chắn rằng ít nhất có tên và họ, được phân tách bằng khoảng trống và chỉ chứa các ký tự bảng chữ cái

Thành phần trong ứng dụng

Cho đến thời điểm này, trình duyệt vẫn hiển thị ứng dụng React đã sẵn sàng. Bây giờ bạn sẽ sửa đổi ứng dụng tệp. js in src directory to display

yarn add zxcvbn isemail prop-types node-sass bootstrap
3  side in AppComponent

Thêm đoạn mã sau

yarn add zxcvbn isemail prop-types node-sass bootstrap
5

Tạo kiểu với Sass

Bạn chỉ còn một bước nữa là hoàn thành ứng dụng của mình. Hiện tại, mọi thứ có vẻ chưa chặt chẽ. Trong bước này, bạn sẽ tiếp tục và xác định một số kiểu cho biểu mẫu

Để tận dụng hết sức mạnh của các biến Sass, cấu trúc lồng [làm tổ] và vòng lặp, trước đây chúng ta đã cài đặt sự phụ thuộc của nút-sass. Bạn đang sử dụng Sass để tạo tệp CSS mà trình duyệt có thể hiểu được

Có hai điều bạn cần thay đổi để sử dụng Sass trong ứng dụng của mình

  • Đổi tên tệp 
    create-react-app react-password-strength
    
    59 thành
    import React, { Component, Fragment } from 'react';
    import PropTypes from 'prop-types';
    class FormField extends Component {
      // initialize state
      state = { value: '', dirty: false, errors: [] }
      hasChanged = e => {
        e.preventDefault[];
        // destructure props - assign default dummy functions to validator and onStateChanged props
        const { label, required = false, validator = f => f, onStateChanged = f => f } = this.props;
        const value = e.target.value;
        const isEmpty = value.length === 0;
        const requiredMissing = this.state.dirty && required && isEmpty;
        let errors = [];
        if [requiredMissing] {
          // if required and is empty, add required error to state
          errors = [ ...errors, `${label} is required` ];
        } else if ['function' === typeof validator] {
          try {
            validator[value];
          } catch [e] {
            // if validator throws error, add validation error to state
            errors = [ ...errors, e.message ];
          }
        }
        // update state and call the onStateChanged callback fn after the update
        // dirty is only changed to true and remains true on and after the first state update
        this.setState[[{ dirty = false }] => [{ value, errors, dirty: !dirty || dirty }], [] => onStateChanged[this.state]];
      }
      render[] {
        const { value, dirty, errors } = this.state;
        const { type, label, fieldId, placeholder, children } = this.props;
        const hasErrors = errors.length > 0;
        const controlClass = ['form-control', dirty ? hasErrors ? 'is-invalid' : 'is-valid' : '' ].join[' '].trim[];
        return [
          
            
    {label} {/** Render the first error if there are any errors **/} { hasErrors &&
    { errors[0] }
    }
    {/** Render the children nodes passed to component **/} {children}
    ]; } } FormField.propTypes = { type: PropTypes.oneOf[["text", "password"]].isRequired, label: PropTypes.string.isRequired, fieldId: PropTypes.string.isRequired, placeholder: PropTypes.string.isRequired, required: PropTypes.bool, children: PropTypes.node, validator: PropTypes.func, onStateChanged: PropTypes.func }; export default FormField;
    0
  • Chỉnh sửa đoạn nhập trong tệp
    import React, { Component, Fragment } from 'react';
    import PropTypes from 'prop-types';
    class FormField extends Component {
      // initialize state
      state = { value: '', dirty: false, errors: [] }
      hasChanged = e => {
        e.preventDefault[];
        // destructure props - assign default dummy functions to validator and onStateChanged props
        const { label, required = false, validator = f => f, onStateChanged = f => f } = this.props;
        const value = e.target.value;
        const isEmpty = value.length === 0;
        const requiredMissing = this.state.dirty && required && isEmpty;
        let errors = [];
        if [requiredMissing] {
          // if required and is empty, add required error to state
          errors = [ ...errors, `${label} is required` ];
        } else if ['function' === typeof validator] {
          try {
            validator[value];
          } catch [e] {
            // if validator throws error, add validation error to state
            errors = [ ...errors, e.message ];
          }
        }
        // update state and call the onStateChanged callback fn after the update
        // dirty is only changed to true and remains true on and after the first state update
        this.setState[[{ dirty = false }] => [{ value, errors, dirty: !dirty || dirty }], [] => onStateChanged[this.state]];
      }
      render[] {
        const { value, dirty, errors } = this.state;
        const { type, label, fieldId, placeholder, children } = this.props;
        const hasErrors = errors.length > 0;
        const controlClass = ['form-control', dirty ? hasErrors ? 'is-invalid' : 'is-valid' : '' ].join[' '].trim[];
        return [
          
            
    {label} {/** Render the first error if there are any errors **/} { hasErrors &&
    { errors[0] }
    }
    {/** Render the children nodes passed to component **/} {children}
    ]; } } FormField.propTypes = { type: PropTypes.oneOf[["text", "password"]].isRequired, label: PropTypes.string.isRequired, fieldId: PropTypes.string.isRequired, placeholder: PropTypes.string.isRequired, required: PropTypes.bool, children: PropTypes.node, validator: PropTypes.func, onStateChanged: PropTypes.func }; export default FormField;
    1

Sau khi đổi tên tệp src/App. css, hãy cập nhật tệp src/App. js của bạn như sau

create-react-app react-password-strength
0

Tiếp theo, mã thay thế hiện có trong tệp Ứng dụng. scss by code after to format app React

create-react-app react-password-strength
1

Bạn đã thành công trong việc bổ sung các phong cách theo ứng dụng của bạn. Lưu ý việc sử dụng nội dung CSS được tạo trong. máy đo cường độ. before and. máy đo cường độ. trước các phần tử để thêm khoảng trống vào máy đo cường độ mật khẩu

Bạn có thể sử dụng Sass 

import React, { Component, Fragment } from 'react';
import PropTypes from 'prop-types';
class FormField extends Component {
  // initialize state
  state = { value: '', dirty: false, errors: [] }
  hasChanged = e => {
    e.preventDefault[];
    // destructure props - assign default dummy functions to validator and onStateChanged props
    const { label, required = false, validator = f => f, onStateChanged = f => f } = this.props;
    const value = e.target.value;
    const isEmpty = value.length === 0;
    const requiredMissing = this.state.dirty && required && isEmpty;
    let errors = [];
    if [requiredMissing] {
      // if required and is empty, add required error to state
      errors = [ ...errors, `${label} is required` ];
    } else if ['function' === typeof validator] {
      try {
        validator[value];
      } catch [e] {
        // if validator throws error, add validation error to state
        errors = [ ...errors, e.message ];
      }
    }
    // update state and call the onStateChanged callback fn after the update
    // dirty is only changed to true and remains true on and after the first state update
    this.setState[[{ dirty = false }] => [{ value, errors, dirty: !dirty || dirty }], [] => onStateChanged[this.state]];
  }
  render[] {
    const { value, dirty, errors } = this.state;
    const { type, label, fieldId, placeholder, children } = this.props;
    const hasErrors = errors.length > 0;
    const controlClass = ['form-control', dirty ? hasErrors ? 'is-invalid' : 'is-valid' : '' ].join[' '].trim[];
    return [
      
        
{label} {/** Render the first error if there are any errors **/} { hasErrors &&
{ errors[0] }
}
{/** Render the children nodes passed to component **/} {children}
]; } } FormField.propTypes = { type: PropTypes.oneOf[["text", "password"]].isRequired, label: PropTypes.string.isRequired, fieldId: PropTypes.string.isRequired, placeholder: PropTypes.string.isRequired, required: PropTypes.bool, children: PropTypes.node, validator: PropTypes.func, onStateChanged: PropTypes.func }; export default FormField;
2 để tự động tạo màu cho máy đo cường độ ở các mật khẩu cường độ khác nhau

Đây là màn hình hoàn chỉnh

Hiển thị thông báo khi báo lỗi nhìn như sau

Trong trường hợp không có lỗi và cường độ cao

Kết luận

Qua bài viết chúng ta có thể kiểm tra độ mạnh yếu của mật khẩu ứng dụng React. Từ đó có thể thêm vào ứng dụng để có trải nghiệm tốt hơn cho người dùng

Chủ Đề