输入字段验证和显示条件

时间:2019-03-24 19:45:11

标签: javascript reactjs

我是javascript的新手,也要对此做出反应。作为家庭作业的一部分,我应该验证输入字段,用户可以在其中输入密码。在此密码字段下,显示了密码必须匹配的条件。密码符合条件时,它们应该从红色变为黑色。该应用程序分为四个不同的组件。

现在的问题是我对react和javascript的理解有限。假设实现的Validation.js逻辑正确,我不知道如何编写一个handleInputChange()函数来将该逻辑与用户输入进行比较。可能有人帮我解决这个问题或给我提示如何进行吗?

谢谢

index.js

import React from "react";
import ReactDOM from "react-dom";
import App from "./App";

ReactDOM.render(<App />, document.querySelector("#root"));

App.js

import React, { Component } from "react";
import Validation from "./Validation";
import Styles from "./Styles";

class App extends Component {
  constructor(props) {
    super(props);

    this.state = {
      value: "",
      conditions: {
        special: false,
        uppercase: false,
        lowercase: false,
        number: false,
        minLength: false
      }
    };
  }

  handleInputChange(e) {
    console.log(e.target.value);

    
  }

  render() {
    return (
      <div className="wrapper">
        <div className="password field">
          <h1>Password Validation</h1>
          <form onSubmit={this.handleSubmit}>
            <div className="Password">
              <label htmlFor="Password" />
              <input
                type="text"
                placeholder="Type password here"
                onChange={this.handleInputChange}
              />
            </div>
            <div className="conditions">
              <p>The password needs to meet the following conditions:</p>
              <ul style={Styles}>
                <li className="special">
                  One Special Character{" "}
                  {this.state.value === this.state.special}
                </li>
                <li className="uppercase">
                  One Letter Uppercase {this.state.value}
                </li>
                <li className="lowercase">
                  One Letter Lowercase {this.state.value}
                </li>
                <li className="number">One Number {this.state.value}</li>
                <li className="minLength">
                  Minimum Length Of 8 Characters {this.state.value}
                </li>
              </ul>
            </div>
            <div>
              <button className="submit button" type="submit">
                Submit
              </button>
            </div>
          </form>
        </div>
      </div>
    );
  }
}

export default App;

Validation.js

import React from "react";

const Validation = value => {
  let special = `!#$%&'()*+,-./:;<=>?@[\]^_{|}~"`;

  for (let i = 0; i < special.length; i++) {
    if (value.indexOf(special[i]) > -1) {
      this.setState({
        special: true
      });
    }
  }

  let uppercase = `ABCDEFGHIJKLMNOPQRSTUVXYZ`;

  for (let i = 0; i < uppercase.length; i++) {
    if (value.indexOf(uppercase[i]) > -1) {
      this.setState({
        uppercase: true
      });
    }
  }

  let lowercase = `abcdefghijklmnopqrstuvxyz`;

  for (let i = 0; i < lowercase.length; i++) {
    if (value.indexOf(lowercase[i]) > -1) {
      this.setState({
        lowercase: true
      });
    }
  }

  let number = `0123456789`;

  for (let i = 0; i < number.length; i++) {
    if (value.indexOf(number[i]) > -1) {
      this.setState({
        number: true
      });
    }
  }

  let minLength = "";

  for (let i = 0; i < minLength.length; i++) {
    if (minLength[i] >= 7) {
      this.setState({
        minLength: true
      });
    }
  }
};

export default Validation;

2 个答案:

答案 0 :(得分:3)

我认为您应该从验证js创建单独的函数并使用它们。 例如:

import Dependencies._

ThisBuild / scalaVersion     := "2.12.5"
ThisBuild / sbtVersion       := "1.2.6"
ThisBuild / version          := "0.1.0-SNAPSHOT"

lazy val root = (project in file("."))
  .settings(
    name := "phenix-challenge",
    libraryDependencies ++= Seq(
      betterFiles,
      scalaz,
      scallop,

      scalaLogging,
      slf4jBackend % Runtime,

      scalaTest % Test
    )
  )

我有一些建议可以改善您的代码和技能:

  • 使用const代替let或var。 link
  • 使用Array的方法(映射,一些,减少,forEach)代替“ for” link
  • 您不能在Validation.js文件中导入React
  • 使用对象分解。例如: //App.js hasSpecial(value) { const special = '!#$%&'()*+,-./:;<=>?@[\]^_{|}~"'; return value.split("").some(char => special.includes(char)); // or with regexp return /[!#$%&'()*+,-.\/:;<=>?@[\]^_{|}~"]/.test(value); } handleInputChange(value) { this.setState({ value, conditions: { special: this.hasSpecial(value) } }); } ... <input type="text" placeholder="Type password here" onChange={e => this.handleInputChange(e.target.value)} value={this.state.value} /> link

答案 1 :(得分:1)

听起来像是使用正则表达式(regEx)的好地方

您可以使用regEx编写一些非常干净的验证代码。

我在这里为您编写了一个示例,但也请参见以下内容: https://codesandbox.io/s/nkqx1zmp6j

从“反应”导入React;

class Input extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      text: "",
      validationError: ""
    };
  }

  handleOnChange = event => {
    this.setState({
      text: event.target.value
    });
  };

  checkPassword = event => {
    event.preventDefault();
    let pattern = /^(?=.*[0-9])(?=.*[!@#$%^&*])(?=.*[a-z])(?=.*[A-Z])[a-zA-Z0-9!@#$%^&*]{5,20}$/;
    let password = this.state.text;

    if (!pattern.test(password)) {
      this.setState({
        validationError:
          "Your password needs a number, special character, lowercase letter, capital letter and can only be between 5 and 20 characters"
      });
    } else {
      console.log(true);
      this.setState({
        validationError: ""
      });
    }
  };
  render() {
    return (
      <div>
        <form onSubmit={this.checkPassword}>
          <input value={this.state.text} onChange={this.handleOnChange} />
          <button type="submit">Submit</button>
        </form>
        <p>{this.state.validationError}</p>
      </div>
    );
  }
}

export default Input;