如何防止密码输入框输入space/whitespace | ReactJs

How to prevent to enter space/whitespace in password input field | ReactJs

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

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);

您需要将输入的值设置为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"]}
        />

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

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

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

只需在 handleOnChange 函数中这样做:

 handleOnChange = (e) => {
    this.setState({
      [e.target.name]: e.target.value.split(" ").join("")
    });
  };

我用正则表达式解决了这个问题

str.replace(/\s/g, '')