react 는 어떻게 암호 강도 감지 기 에 대한 상세 한 설명 을 실현 합 니까?
암호 강도 파일 검사 기;계 정 을 등록 할 때 우 리 는 사용자 의 현재 암호 강 도 를 평가 해 야 한다.이 과정 에서 우 리 는 검 측 기 를 만들어 야 한다.가장 유연 하 게 쓰 는 것 이 제품 이 규칙 을 수정 하 는 데 편리 하 다.
일단 효 과 를 볼 게 요. 다음은 캡 처 에 대응 하 는 상태 입 니 다.
 쓰다
1 매개 변수 전달
const PasswordForce = passwordForce({ inputValue, className: 'password-force', });
2 사용
3 검사
문자 초과 여 부 를 검사 합 니 다
PasswordForce.invaildWord실현 예다음 비밀번호 입력 상자 에 알림 기 를 연결 하도록 antd 를 설정 합 니 다.
1,2 는 고 칠 필요 가 없 지만 실제로 input 의 값 을 감청 하고 값 을 설정 해 야 합 니 다.그래서 우 리 는 감청 수정 value 의 함 수 를 정의 할 수 있다.
const [inputValue, setInputValue] = useState('');
    const passwordChange = (value: string) => {
    setInputValue(value);
};
const onPasswordInput = (e: any) => {
    passwordChange(e?.target?.value || '');
};
그리고 바 인 딩 을 하면 됩 니 다.바 인 딩 을 하면 정상적으로 표시 할 수 있 습 니 다.하지만 불법 문 자 를 입력 하면 차단 기 를 통 해 차단 해 야 합 니 다.
<Form.Item
...
rules={[
    {
      required: true,
      message: 'Password not empty',
    },
    ({ getFieldValue }) => ({
      validator(_, value) {
        passwordChange(value);
        if (PasswordForce.invaildWord) {
          return Promise.reject(
            new Error('Password contains invalid characters.'),
          );
        }
        return Promise.resolve();
      },
    }),
]}
...
자,필름 사용 이 끝 났 으 니 우리 실현 합 시다.구성 요소 작성
구성 요소 작성
import {
  getRuleMatchResult,
  IpasswordForce,
  IpasswordRule,
  isMatchForceResultConfig,
  matchResultConfig,
  passwordBreakKey,
} from '@/utils/passwordStrengthChecker';
import React, { CSSProperties } from 'react';
import { useEffect } from 'react';
import { useState } from 'react';
import styled from 'styled-components';
interface props {
  inputValue: string;
  color?: string;
  style?: CSSProperties;
  className?: string;
  customRule?: IpasswordRule[];
}
enum ForceMap {
  high = 'High',
  middle = 'Mid',
  low = 'Low',
}
const boolNumSum = (list: boolean[]) =>
  list.reduce<number>(
    (previousValue, currentValue) =>
      currentValue ? previousValue + 1 : previousValue,
    0,
  );
const passwordForce: (props: props) => {
  View: React.FC;
  invaildWord: boolean;
  force: IpasswordForce;
} = ({ inputValue, style = {}, className, customRule = [] }) => {
  const [force, setforce] = useState<IpasswordForce>(false);
  const [invaildWord, setIsInvaildWord] = useState(false);
  const inputValueLen = inputValue?.length || 0;
  const setData = () => {
    setforce(false);
    const isFirstWordUp = inputValue[0] === inputValue[0].toLocaleUpperCase();
    const ruleRsult = getRuleMatchResult(customRule, inputValue, undefined, '');
    const matchNum = boolNumSum(ruleRsult.list.map((e) => e[passwordBreakKey]));
    const matchResultConfig: matchResultConfig[] = [
      { min: 0, max: 32, matchNum: 1, value: 'low' },
      { min: 7, max: 32, matchNum: 2, value: 'middle' },
      { min: 7, max: 32, matchNum: 3, value: 'middle' },
      { min: 15, max: 32, matchNum: 3, value: 'high', need: isFirstWordUp },
    ];
    setIsInvaildWord(ruleRsult.invaildWord);
    matchResultConfig.forEach((config) => {
      isMatchForceResultConfig(config, matchNum, inputValueLen) &&
        setforce(config.value);
    });
  };
  useEffect(() => {
    inputValue ? setData() : setforce(false);
  }, [inputValue]);
  return {
    View: () =>
      force ? (
        <PasswordForceWrap {...{ style, className }}>
          {ForceMap[force]}
        </PasswordForceWrap>
      ) : (
        <></>
      ),
    invaildWord,
    force,
  };
};
export default passwordForce;
const PasswordForceWrap = styled.span`
  color: ${({ color }) => color ?? '#000'};
`;
데이터 구조 분석4.567917.list 규칙 의 집합 은 모든 규칙 이 규칙 명 과 이미 규칙 적 인 데이터 자체 에 일치 하 는 지 여부 입 니 다4.567917.map 는 해당 규칙 의 데 이 터 를 직접 얻 기 편리 하 다matchCount 는 일치 하 는 문자 수 입 니 다
이 건 사실 두 가지 절차 에 요.
4.567917.입력 한 값 과 규칙 에 따라 처 리 된 데 이 터 를 얻 고 얻 은 데이터 구 조 는 위 와 같다
바 텀 코드 분석
우리 건강 합 시다.
다음은 순수 ts 코드 입 니 다.임의의 프레임 워 크 를 실행 할 수 있 습 니 다.
passwordStrengthChecker.ts
import { numberList, specialList, wordList } from './constants';
type map = <U, T>(opstion: {
  array: U[];
  range: number;
  matchList: T[];
  tokenMap: (updateItem: T, token: U, index: number) => T;
  breakKey?: string;
  arrayMap?: (item: U, index: number) => void;
}) => T[];
/**
 * match array and set
 */
export const setArrayMatch: map = ({
  array,
  range,
  matchList,
  breakKey,
  tokenMap,
  arrayMap,
}) => {
  const tokenLen = array.length;
  for (let tokenIndex = tokenLen - 1; tokenIndex >= 0; tokenIndex--) {
    const arrayToken = array[tokenIndex];
    arrayMap && arrayMap(arrayToken, tokenIndex);
    for (let findIndex = range - 1; findIndex >= 0; findIndex--) {
      matchList = matchList.map((item) =>
        tokenMap(item, arrayToken, findIndex),
      );
    }
    if (breakKey && !matchList.map((e) => (e as any)[breakKey]).includes(false))
      break;
  }
  return matchList;
};
export const passwordBreakKey = 'isMatch';
export type IpasswordRule = {
  list: string[];
  isMatch: boolean;
  name: string;
};
export const defaultPasswordRuleList = [
  { name: 'special', list: specialList },
  { name: 'num', list: numberList },
  { name: 'word', list: wordList },
];
type PickValue<T, K extends keyof T> = T[K];
export const getRuleMatchResult: (
  customRule: IpasswordRule[],
  inputValue: string,
  disableDefaultRule?: boolean,
  breakKey?: string,
) => {
  list: IpasswordRule[];
  map: Map<PickValue<IpasswordRule, 'name'>, boolean>;
  matchCount: number;
  invaildWord: boolean;
} = (customRule, inputValue, disableDefaultRule = true, breakKey) => {
  let ruleList = [
    ...(disableDefaultRule ? defaultPasswordRuleList : []),
    ...customRule,
  ].map((item) => ({ ...item, [passwordBreakKey]: false }));
  const range = Math.max(...ruleList.map((ruleItem) => ruleItem.list.length));
  let matchCount = 0;
  ruleList = setArrayMatch<string, IpasswordRule>({
    array: inputValue.split(''),
    range,
    matchList: ruleList,
    // not breakKey  full match
    breakKey: breakKey === void 0 ? passwordBreakKey : breakKey,
    tokenMap: (ruleItem, inputToken, findIndex) => {
      const match = ruleItem?.list[findIndex] === inputToken;
      if (match) {
        matchCount++;
        return { ...ruleItem, isMatch: true };
      }
      return ruleItem;
    },
  });
  return {
    list: ruleList,
    map: new Map(ruleList.map((e) => [e.name, e[passwordBreakKey]])),
    matchCount,
    //        ,  breakKey      ,               
    // To get this value, breakkey must be set to null string
    invaildWord: matchCount !== inputValue.length,
  };
};
export const isMatchForceResultConfig = (
  config: matchResultConfig,
  matchNum: number,
  inputValueLen: number,
) => {
  return (
    matchNum === config.matchNum &&
    inputValueLen >= config.min &&
    inputValueLen <= config.max &&
    (config.need !== undefined ? config.need : true)
  );
};
export type matchResultConfig = {
  min: number;
  max: number;
  matchNum: number;
  value: IpasswordForce;
  need?: boolean;
  back?: IpasswordForce;
};
export type IpasswordForce = false | 'high' | 'middle' | 'low';
프로 세 스 는 병합 규칙 입 니 다.하 나 는 기본 규칙 이 고 하 나 는 사용자 정의 규칙 입 니 다.사용자 정의 규칙 이 있 으 면 기본 규칙 을 덮어 씁 니 다.규칙 에서 규칙 의 수량 이 가장 긴 규칙 을 찾 습 니 다.다음 에 우리 가 옮 겨 다 닐 때 모든 규칙 을 합병 할 수 있 기 때 문 입 니 다.아무리 많은 규칙 이 있어 도 사실은 횟수 의 차이 가 크 지 않 습 니 다.
스 트 리밍 함 수 는 단독 고급 함수 로 내부 의 논 리 를 사용자 정의 로 처리 할 수 있 습 니 다.이때 우 리 는 그 후에 대응 하 는 규칙 과 일치 하여 해당 하 는 규칙 의 속성 을 활성화 하고 일치 하 는 문 자 를 누적 할 수 있 습 니 다.
마지막 으로 정상적으로 일치 하면 옮 겨 다 니 는 것 을 중지 해 야 하지만 중단 할 수 없 는 경우 가 있 습 니 다.불법 문자 가 있 는 지 판단 해 야 합 니 다.
마지막 으로 이 함 수 는 처 리 된 데 이 터 를 상부 구성 요소 에 버 렸 습 니 다.절 차 는 바로 이 렇 습 니 다.
데 이 터 를 던 지 는 과정 에서 일부 장면 은 해당 규칙 의 데 이 터 를 특수 처리 해 야 할 수도 있 지만 array 구조 라면 불편 하기 때문에 던 진 데 이 터 는 list 와 map 유형 으로 나 누 어야 합 니 다.상부 응용 프로그램 에서 해당 규칙 을 가 져 오 려 면 map.get(규칙 이름)으로 조작 할 수 있 습 니 다.
constants.ts
export const specialList = ["~", "!", "@", "#", "$", "%", "^", "&", "*", "(", ")", "_", "=", "-", "/", ",", ".", "?", "<", ">", ";", ":", "[", "]", "{", "}", "|", "\\"];
export const numberList = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '0'];
export const wordList = ["q", "a", "z", "w", "s", "x", "e", "d", "c", "r", "f", "v", "t", "g", "b", "y", "h", "n", "u", "j", "m", "i", "k", "o", "l", "p", "Q", "A", "Z", "W", "S", "X", "E", "D", "C", "R", "F", "V", "T", "G", "B", "Y", "H", "N", "U", "J", "M", "I", "K", "O", "L", "P"];
기타많은 사람들 이 의문 을 가 질 수 있 습 니 다.코드 감지 기 가 이렇게 복잡 할 필요 가 있 습 니까?바로 정칙 이 좋 지 않 습 니까?사실 실 용적 인 측면 에서 볼 때 확실히 더 편리 하 다.그러나 가끔 우 리 는 규칙 을 따 르 거나 수 동 으로 인 코딩 하 는 쾌감 을 원 하지 않 거나 지루 한 코드 에서 더 많은 놀 수 있 는 성 을 얻 으 려 고 하기 때문에 복잡 해 보 이 는 코드 를 만 들 지만 바닥 을 봉 한 다음 에 유연성 을 유지 하고 업무 층 에서 최대한 간단하게 한다.사실 해 볼 수 없 는 것 도 아니 지만 review 할 때 도 24636 에 의 해 복 사 될 수 있 습 니 다.여러분,시간 이 촉박 하거나 인 코딩 능력 이 강하 지 않 으 면 본 코드 를 사용 하 는 것 을 권장 하지 않 습 니 다.문제 가 생기 면 본인 은 일체 책임 을 지지 않 습 니 다.
총결산
여기 서 react 가 암호 강도 감지 기 를 어떻게 실현 하 는 지 에 관 한 글 은 여기까지 소개 되 었 습 니 다.더 많은 react 암호 강도 감지 기 내용 은 우리 의 이전 글 을 검색 하거나 아래 의 관련 글 을 계속 조회 하 시기 바 랍 니 다.앞으로 많은 응원 바 랍 니 다!
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
nginx 에서 사이트 아이콘 표시 설정전단 개발 환경: react:^16.4.1 webpack:^4.16.0 웹 팩 에 favicon. ico 설정 추가: nginx 는 ico 에 대한 지원 을 추가 합 니 다:...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.