Home>
What i am doing now

We have created a registration screen to check validation in real time using react.js

Problem

See three conditions when checking password values ​​
→ Isn't it possible to put together the values ​​passed to the child components?

Code (I wrote a question in the code)
function PasswordBallon (props) {
      return (
          <div className = "passwordBallon">{props.NumberOfPassword}
            <ul>
                <span className = "title">Password rules</span>
                <li>// ** ①Can the following conditional branches be shortened?
                    {(() =>{
                      if (props.NumberOfPassword == true) {
                        return<img src = "../ img/check-solid.svg" style = {{height: "22px"}} />
                    } Else {
                        return<img src = "../ img/baseline-error_outline-24px.svg" />
                    }
                    }) ()}
                    {(() =>{
                      if (props.NumberOfPassword == true) {
                        return<span style = {{color: "# E4E7E8"}}> 8 characters minimum</span>
                    } Else {
                        return<span> 8 characters minimum</span>
                    }
                    }) ()}
                </li>
                <li>
                    {(() =>{
                      if (props.CheckNumber == true) {
                        return<img src = "../ img/check-solid.svg" style = {{height: "22px"}} />
                    } Else {
                        return<img src = "../ img/baseline-error_outline-24px.svg" />
                    }
                    }) ()}
                    {(() =>{
                      if (props.CheckNumber == true) {
                        return<span style = {{color: "# E4E7E8"}}> Contains at least 1 number</span>
                    } Else {
                        return<span> Contains at least 1 number</span>
                    }
                    }) ()}
                </li>
                <li>
                    {(() =>{
                      if (props.CheckCharacter == true) {
                        return<img src = "../ icon/check-solid.svg" style = {{height: "22px"}} />
                    } Else {
                        return<img src = "../ icon/baseline-error_outline-24px.svg" />
                    }
                    }) ()}
                    {(() =>{
                      if (props.CheckCharacter == true) {
                        return<span style = {{color: "# E4E7E8"}}> Can't be "password", "username"</span>
                    } Else {
                        return<span> Can't be "password", "username"</span>
                    }
                    }) ()}
                </li>
            </ul>
          </div>
      );
  }
    class App extends React.Component {
        constructor () {
          super ();
          this.state = {
            display: false,
            fields: {},
            errors: {},NumberOfPassword: false,
            CheckNumber: false,
            CheckCharacter: false,
          };
          this.passwordClick = this.passwordClick.bind (this);
        }

        passwordClick () {
            this.setState ({
              display: true
            });
         }
         handleChange (field, e) {
            let errors = {};
            let fields = this.state.fields;
            fields [field] = e.target.value;
            this.setState ({fields});
            if (! fields ["password"]) {
            // formIsValid = false;
               errors ["EmptyPassword"] = "Cannot be empty";
            }
            if (typeof fields ["password"]! == "undefined") {
               if (fields ["password"]. match (/ ^. {8,} $/)) {
                // formIsValid = false;
                  this.setState ({NumberOfPassword: true});
               } else {
                   this.setState ({NumberOfPassword: false});
               }
               if (fields ["password"]. match (/ [0-9] /)) {
                // formIsValid = false;
                  this.setState ({CheckNumber: true});
               } else {
                   this.setState ({CheckNumber: false});
               }
               if (fields ["password"]! = ("password" || "user")) {
                  this.setState ({CheckCharacter: true});
               } else {
                   this.setState ({CheckCharacter: false});
               }
            }
         }
        //// component name should be capitalized first **
        render () {
          return (
            <div className = 'signup'>
              <h1>Create Account</h1>
              <div><input type = "text" name = "name" placeholder = "name" /></div>
              <div><input type = "text" name = "email" placeholder = "email" /></div>
              <div className = "wrapperPassword">
                <input type = "password" name = "password" placeholder = "password"
                    onClick = {this.passwordClick}
                    onChange = {this.handleChange.bind (this, "password")}
                    value = {this.state.fields ["password"]}
                />
                {this.state.display?<PasswordBallon // ** ② Can you put together a state that checks the password conditions here? ?
                                        NumberOfPassword = {this.state.NumberOfPassword}
                                        CheckNumber = {this.state.CheckNumber}
                                        CheckCharacter = {this.state.CheckCharacter} /&gt ;: null}
              </div>
              <div><input type = "text" name = "passConfirm" placeholder = "confirm password" /></div>
            </div>
          );
        }
    }
    ReactDOM.render (
      <App /&gt ;,
      document.getElementById ('wrapper')
    );
}) ();
  • Answer # 1

    https://codesandbox.io/s/k04v88ljpv

    import React from "react";
    import ReactDOM from "react-dom";
    / **
     * @param {Object} props
     * @param {boolean} props.isValid
     * @param {string} props.text
     * @return {JSX.Element}
     * /
    const ValidationResultList = ({isValid, text}) =>{
      const imgStyle = isValid? {height: "22px"}: {};
      const imgSrc = isValid
        ? "../img/check-solid.svg"
        : "../img/baseline-error_outline-24px.svg";
      const spanStyle = isValid? {color: "# E4E7E8"}: {};
      return (
        <li>
          <img style = {imgStyle} src = {imgSrc} />
          <span style = {spanStyle}>{text}</span>
        </li>
      );
    };
    / **
     * @param {Object} props
     * @param {boolean} props.invalidLength
     * @param {boolean} props.notContainNumber
     * @param {boolean} props.blacklistedWord
     * @return {JSX.Element}
     * /
    const PasswordBallon = ({
      invalidLength,
      notContainNumber,
      blacklistedWord
    }) =>{
      return (
        <div className = "passwordBallon">
          <ul>
            <span className = "title">Password rules</span>
            <ValidationResultList
              isValid = {! invalidLength}
              text = {"&nbsp;8 characters minimum"}
            />
            <ValidationResultList
              isValid = {! notContainNumber}
              text = {"&nbsp;Contains at least 1 number"}
            />
            <ValidationResultList
              isValid = {! blacklistedWord}
              text = {'&nbsp;Can \' t be "password", "username" '}
            />
          </ul>
        </div>
      );
    };
    class App extends React.Component {
      constructor () {
        super ();
        this.state = {
          name: {
            value: "",
            isDirty: false,
            error: null
          },
          email: {
            value: "",
            isDirty: false,
            error: null
          },
          password: {
            value: "",
            isDirty: false,
            error: {
              invalidLength: false,
              notContainNumber: false,
              blacklistedWord: false
            }
          },
          passwordConfirm: {
            value: "",
            isDirty: false,
            error: null
          }
        };
        this.onChangePassword = this.onChangePassword.bind (this);
      }
      // Should I cut validation out of class?
      onChangePassword (event) {
        const currentValue = event.target.value;
        let invalidLength = false;
        let notContainNumber = false;
        let blacklistedWord = false;
        if (typeof currentValue! == "string" || currentValue.length<1) {
          invalidLength = true;
        } else {
          invalidLength =! currentValue.match (/ ^. {8,} $/);
          notContainNumber =! currentValue.match (/ [0-9] /);
          blacklistedWord = ["password", "user"]. includes (currentValue);
        }
        this.setState ({
          password: {
            value: currentValue,
            isDirty: true,
            error: {
              invalidLength,
              notContainNumber,
              blacklistedWord
            }
          }
        });
      }
      showPasswordBaloon () {
        const {isDirty, error} = this.state.password;
        if (! isDirty) return false;
        return true;
        / * If everything is OK, if you want to turn off the balloon
        for (let v of Object.values ​​(error)) {
          if (v) return true;
        }
        return false
        * /
      }
      render () {
        return (
          <div className = "signup">
            <h1>Create Account</h1>
            <div>
              <input type = "text" name = "name" placeholder = "name" />
            </div>
            <div>
              <input type = "text" name = "email" placeholder = "email" />
            </div>
            <div className = "wrapperPassword">
              <input
                type = "password"
                name = "password"
                placeholder = "password"
                onChange = {this.onChangePassword}
                value = {this.state.password.value}
              />
              {this.showPasswordBaloon ()? (
                <PasswordBallon {... this.state.password.error} />
              ): (
                ""
              )}
            </div>
            <div>
              <input
                type = "text"
                name = "passConfirm"
                placeholder = "confirm password"
              />
            </div>
          </div>
        );
      }
    }
    ReactDOM.render (<App /> ;, document.getElementById ("root"));

Related articles