Search code examples
javascriptreactjssemantic-ui-react

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


Here I provide my code where I want to enter characters into the password input field and I want to do not enter whitespace/space in it but it also going inside of it instead when I print input value then it does not contain space/whitespace. Please help me to resolve the issue.

CodeSandBox Demo

Code -

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

Solution

  • You need to set the value of the input to inputFieldData.pass.val,
    otherwise it is 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"]}
            />