javascript - react / react Hook : I need to run a validation on an input field depending on active/inactive state

标签 javascript reactjs validation

我有一个使用 React 钩子(Hook)创建的组件,该组件具有输入和复选框。我已将一个函数附加到输入以验证电子邮件地址。我在清除输入并禁用它的复选框上有一个功能。我正在尝试重写我的验证函数以在输入字段处于事件状态时运行,这样即使用户单击复选框以清除和禁用该字段然后再次单击它以重新启用它,验证也会再次运行并提示带有错误消息的用户输入电子邮件地址。到目前为止,我的输入设置了一个 onBlur 函数,该函数在用户输入和退出输入时立即运行验证。我需要维护此功能,但增加它以在启用输入时也运行。我有一个代码沙箱 here有关更多上下文和我的以下简短格式的组件:

import React from "react";
import PropTypes from "prop-types";
import styled from "styled-components";
import { Col, Row, Input, Checkbox } from "antd";

function validateEmail(value) {
  const errors = {};
  if (value === "") {
    errors.email = "Email address is required";
  } else if (!/\S+@\S+\.\S+/.test(value)) {
    errors.email = "Email address is invalid";
  }
  return errors;
}

const CustomerDetails = ({ customer }) => {
  const { contact = {} } = customer || {};
  const [disableInput, setDisableInput] = React.useState(false);
  const [errors, setErrors] = React.useState({});
  const [inputValue, setInputValue] = React.useState(contact.email);

  function onBlur(e) {
    setErrors(validateEmail(e.target.value));
  }

  function clearInput() {
    setInputValue(" ");
  }

  function handleInputChange(event) {
    setInputValue(event.target.value);
  }

  function CheckboxClick(e) {
    if (!disableInput) {
      clearInput();
    }
    setDisableInput(prevValue => !prevValue);
    setErrors({});
  }

  return (
    <Container>
      <Row>
        <Col span={8}>
          <StyledInput
            value={inputValue}
            onChange={handleInputChange}
            disabled={disableInput}
            onBlur={onBlur}
            isError={!!errors.email}
          />
          {errors.email && <ErrorDiv>{errors.email}</ErrorDiv>}
        </Col>
        <Col span={8}>
          <Checkbox value={disableInput} onChange={CheckboxClick} /> EMAIL OPT
          OUT
        </Col>
      </Row>
    </Container>
  );
};

const Container = styled.div`
  text-align: left;
`;

const ErrorInput = ({ isError, ...remainingProps }) => (
  <Input {...remainingProps} />
);

ErrorInput.propTypes = {
  isError: PropTypes.bool
};

const StyledInput = styled(ErrorInput)`
  max-width: 100%;
  background: white;

  &&& {
    border: 2px solid ${props => (props.isError ? "#d11314" : "black")};
    border-radius: 0px;
    height: 35px;
  }
`;

const ErrorDiv = styled.div`
  color: #d11314;
`;

export default CustomerDetails;

最佳答案

你可以做类似的事情

function CheckboxClick(e) {
  const isDisabled = !disableInput;
  setDisableInput(isDisabled);

  if (isDisabled) {
    clearInput();
    setErrors({});
  } else {
    setErrors(validateEmail(inputValue));
  }
}

因此,首先更新 disabled 状态,然后根据它执行操作。

关于javascript - react / react Hook : I need to run a validation on an input field depending on active/inactive state,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56548944/

相关文章:

JavaScript 表单验证,返回 False

spring - 如何在 freemarker 模板中显示验证错误

javascript - 如何比较两个日期并根据差异返回年份或日期?

javascript - 如果 Javascript 中的变量低于零,则使用 while 循环显示消息

javascript - 使用 React 设置 React-Redux

javascript - 使用 React Router 和 Webpack 2 如何仅在某些路由上需要外部库?

javascript - 如何将事件附加到 TileMill 中创建的 Natural Earth map 数据?

javascript - D3 : event functions with concatenated transitions

javascript - 使用多个 Not Acceptable prop值时,为什么我的React propTypes的Jest测试会中断?

ruby-on-rails - 您如何针对多个正则表达式进行验证?