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

标签 javascript reactjs semantic-ui-react

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

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

最佳答案

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

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

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

关于javascript - 如何防止在密码输入字段中输入空格/空白 | ReactJs,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55017746/

相关文章:

javascript - 使用 WebCrypto 进行 AES 加密数据长度

javascript - eslint 规则禁止在赋值等号后换行(即 var foo =\n 42)

javascript - 使用 React.js 渲染 JSON

html - 在垂直菜单语义 UI React 上添加 float 标签时分隔线消失

javascript - React Router 和 Semantic UI React 的问题

javascript - 在 Chrome 中,为什么 TypedArrays 不在 JS 堆上?

javascript - 在 Node.js 中使用 PUT 删除

reactjs - 无法覆盖react-native的TextInput默认填充

reactjs - 错误 shallow Jest Enzyme React 找不到 "store"

javascript - 如何在 React 中定义 setFieldValue