13

I have a simple form that receives the first name and last name, and I need to remove the whitespaces in the beginning and end of the string. I can do this with the .trim() method, but because is a form, it doesn't let me write a name that has two words, such as Ana Maria, because it doesn't let me press the space key at the end of a word. How can I remove white spaces from both sides of a string but still let me press space and write more than one word?

enter image description here

This is the component:

export default function ScheduleInput(
  { label, required, onChange, value, ...extraProps },
) {
  return (
    <div className="item_container">
      {label}:
      {required &&
        <span style={{ color: 'red' }}> *</span>
      }
      <br />
      <input
        type="text"
        onChange={onChange}
        value={value.trim()}
        {...extraProps}
      />
    </div>
  );
}
Lizz Parody
  • 1,705
  • 11
  • 29
  • 48
  • 1
    I think you should let the user type what he wants and use `trim` function into a `onBlur` event to validate the data when the user leave the field, if you use `trim` into the `onChange` handler, he won't be able to use the space character – Olivier Boissé Sep 11 '18 at 21:20
  • Do you mean? `string.trimLeft().trimRight()`? – Ashish Sep 11 '18 at 21:20
  • Either trim on blur or trim before submit of data, I usually trim and validate b4 submission. – mattdevio Sep 11 '18 at 21:22
  • @Ashish https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/Trim – coreyward Sep 11 '18 at 21:22
  • @coreyward Yeah sure, `trim` is good, just thought for a second, can using the left & right specifically get you faster times? But anyway, looks like, that right now isn't exactly the concern. – Ashish Sep 11 '18 at 21:38

1 Answers1

23

Instead of trimming onChange, do that in an onBlur callback:

<input onBlur={this.props.formatInput} {...} />

Where that might look something like this:

formatInput = (event) => {
  const attribute = event.target.getAttribute('name')
  this.setState({ [attribute]: event.target.value.trim() })
}
coreyward
  • 77,547
  • 20
  • 137
  • 166