如何防止在密码输入字段中输入空格/空格ReactJs

问题描述 投票:1回答:2

在这里,我提供了我想要在密码输入字段中输入字符的代码,我想不要在其中输入空格/空格,但是当我打印输入值然后它不包含空格/空格时它也会进入其中。请帮我解决这个问题。

CodeSandBox Demo

代码 -

import React from "react";
import ReactDOM from "react-dom";
import "./styles.css";
import { Form, Input, Label } from "semantic-ui-react";

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      inputFieldData: {
        pass: {
          val: "",
          error: false
        }
      }
    };
  }

  inputChange = e => {
    // prevent not to enter space charactes in password field while registering
    const re = /^\S*$/;
    let inputFieldData = this.state.inputFieldData;
    const name = e.target.name;
    if (re.test(e.target.value)) {
      inputFieldData[name]["val"] = e.target.value;
      console.log(e.target.value);
    }
    this.setState({ inputFieldData });
  };

  render() {
    const { inputFieldData } = this.state;

    return (
      <div className="App">
        <h1>Input box does not contain space in it</h1>
        <h3>Input Value: {inputFieldData["pass"]["val"]}</h3>
        <Form className="register-form">
          <Form.Field>
            <Input
              type="password"
              icon="user circle"
              name="pass"
              iconPosition="left"
              placeholder="Enter Password"
              onChange={this.inputChange}
              error={inputFieldData["pass"]["error"]}
            />
            {inputFieldData["pass"]["error"] && (
              <Label basic color="red" pointing>
                Field can not be empty
              </Label>
            )}
          </Form.Field>
        </Form>
      </div>
    );
  }
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
javascript reactjs semantic-ui-react
2个回答
1
投票

您需要将输入值设置为inputFieldData.pass.val, 否则就是not bound to the state of your component

        <Input
          value={inputFieldData.pass.val}
          type="password"
          icon="user circle"
          name="pass"
          iconPosition="left"
          placeholder="Enter Password"
          onChange={this.inputChange}
          error={inputFieldData["pass"]["error"]}
        />

0
投票

您需要通过将https://reactjs.org/docs/forms.html#controlled-components prop添加到value组件来使用受控组件模式(请参阅此处input)。

然后,您可以在handleChange函数中添加空间修剪逻辑。

这是一个例子:https://codesandbox.io/s/kkpr53k36r

© www.soinside.com 2019 - 2024. All rights reserved.