是的,使用可重复使用的组件来验证密码

我正在研究重用组件方面,因此props经常被使用:) 我想验证密码字段

import React, { useState, useCallback } from 'react';
import { TextInputProperties } from 'react-native';
import * as yup from 'yup';
import { Col, InputLabel, BaseInput, ErrorLabel } from '../base-input';

interface BaseInputProps extends TextInputProperties {}

const passwordSchema = yup.string().required('Field required');
const confirmPasswordSchema = yup.string().required('Confirm Password is required').when('password', {
  is: val => (val && val.length > 0 ? true : false),
  then: yup
    .string()

    .oneOf([yup.ref('password')], 'Both password need to be the same'),
});

interface PasswordInputProps extends BaseInputProps {
  label?: string;
  id?: string;
  onValidPassword?: (password: string | undefined) => any;
}

export const PasswordInputs = (props: PasswordInputProps) => {
  const [invalidPassword, setInvalidPassword] = useState<string | undefined>(
    undefined
  );
  const checkPassword = useCallback(
    async passwordFieldId => {
      if (props.onChangeText) props.onChangeText(passwordFieldId);
      if (props.id === 'password') {
        try {
          await passwordSchema.validate(passwordFieldId);
          if (props.onValidPassword) props.onValidPassword(passwordFieldId);
          if (invalidPassword) setInvalidPassword(undefined);
        } catch (e) {
          if (e instanceof yup.ValidationError) {
            if (props.onValidPassword) props.onValidPassword(undefined);
            setInvalidPassword(e.message);
          }
        }
      } else {
        try {
          await confirmPasswordSchema.validate(passwordFieldId);
          if (props.onValidPassword) props.onValidPassword(passwordFieldId);
          if (invalidPassword) setInvalidPassword(undefined);
        } catch (e) {
          if (e instanceof yup.ValidationError) {
            if (props.onValidPassword) props.onValidPassword(undefined);
            setInvalidPassword(e.message);
          }
        }
      }
    },
    [props.onChangeText, props.onValidPassword, invalidPassword]
  );
  return (
    <Col>
      <InputLabel>{props.label}</InputLabel>
      <BaseInput
        id={props.id}
        style={{ marginBottom: 10 }}
        secureTextEntry={false}
        onChangeText={checkPassword}
        {...props}
      />
      {invalidPassword && <ErrorLabel>{invalidPassword}</ErrorLabel>}
    </Col>
  );
};

我想验证密码和确认密码这两个字段,我承认目前我的逻辑还不是很不错,我仍然想弄清楚这一点,但这是我所能达到的。

从故事书:

export const Password = () => {
  return (
    <div style={{ padding: '20px' }}>
     <PasswordInputs onValidPassword={action('password')} label='Password' id='password'/>
      <PasswordInputs onValidPassword={action('confirmPassword')} label='Confirm Password' id='confirmPassword'/>
    </div>
  );
};

我想检查密码并确认密码并验证是否匹配。

评论