smit
smit

Reputation: 282

Not allowing space in input field React

I have got a register form which sends request with the first and last name and works fine. But, when a user enters whitespace it considers it as a valid input. The validation errors are sent from the api's response where a blank input gives an error. I tried to trim the firstname in submit() thinking that it it has spaces, it will remove it and consider as a blank input. But this doesnt seem to work. How can I implement the logic for it to trim the whitespace and not allow it.

export default class Signup extends Form {
    constructor(props, context) {
        super(props, context);
        this.state = {                
            firstName: '',
            lastName: '',        
        };
    
        this.handleChange = this.handleChange.bind(this);

    }

    
    submit() {          
        let firstName=this.state.firstName.trim(); 
       
        return this.app.register({
            firstName: firstName,
            lastName: this.state.lastName,
        }).then(account => success())
        .catch(e => {
            this.setState({ error: `signup_form_error_${e}` });
          })    
    }
    
    handleChange(event) {
        this.setState({
            [event.target.name]: event.target.value
        })
    }

    render(props, state) {


        return <form onSubmit={this.form.submit} name="signup" noValidate>
          <input type="text" name="firstName" value={this.state.firstName} onChange={this.handleChange} />
            <input type="text" name="lastName" value={this.state.lastName} onChange={this.handleChange} />
       

            <div class="s72-buttons">
                <button type="submit"</button>
            </div>
        </form>;
    }
}

Upvotes: 3

Views: 16134

Answers (3)

Rafael Dinov
Rafael Dinov

Reputation: 1

react hook form:

<input
    {...register('newPassword')}
     onChange={(evt) =>
         setValue(
             'newPassword',
              evt.currentTarget.value.replace(/ /g, '')
          )
        }
     name='newPassword'
     type='text'
/>

only react:

<input
    onChange={(evt) => evt.currentTarget.value.replace(/ /g, '')}
    name='newPassword'
    type='text'
/>

Upvotes: 0

zhuhang.jasper
zhuhang.jasper

Reputation: 4465

For those using react hook form controller

You can modify the onChange handler like below, to prevent user from typing spaces at all.

<Controller
  name='username'
  control={control}
  rules={{ required: true }}
  render={({ field: { value, onChange, onBlur } }) => (
    <TextField
      autoComplete='new-password'
      label='Username'
      value={value}
      onBlur={onBlur}
      onChange={(e) => {
        onChange(e.target.value.trim());
      }}
      error={Boolean(errors.username)}
      inputProps={{ tabIndex: 1, style: { textTransform: "lowercase" } }}
    />
  )}
/>

Or alternatively, you can do it after onBlur (Below code is to remove consecutive spaces)

const removeExtraSpace = (s: string) => s.trim().split(/ +/).join(" ");

<Controller
  name='fullName'
  control={control}
  rules={{ required: true }}
  render={({ field: { value, onChange, onBlur } }) => (
    <TextField
      label='Full Name'
      value={value}
      onBlur={() => {
        onBlur();
        onChange(removeExtraSpace(value));
      }}
      onChange={onChange}
      error={Boolean(errors.fullName)}
      inputProps={{ tabIndex: 2 }}
    />
  )}
/>

Upvotes: 0

Ernesto
Ernesto

Reputation: 4252

The error lives in your onSubmit at your <form/> you have it like this

this.form.submit

but this.form does not exists, there for the default behavior takes place

export default class Signup extends React.Component {
    constructor(props) {
        super(props);
        this.state = {                
            firstName: '',
            lastName: '',        
        };
    
        this.handleChange = this.handleChange.bind(this);
        this.submit = this.submit.bind(this);

    }

    
    submit(event) {
        event.preventDefault();          
        const regexp = /^\S*$/; 
        const { firstName,lastName }= this.state; 
       
       if (!regexp.test(firstName) || !regexp.test(lastName)) {
         // cancel process, whitespace found;

         return;
       }

        return this.app.register({
            firstName: firstName,
            lastName: this.state.lastName,
        }).then(account => success())
        .catch(e => {
            this.setState({ error: `signup_form_error_${e}` });
          })    
    }
    
    handleChange(event) {
        this.setState({
            [event.target.name]: event.target.value.trim();
        })
    }

    render(props, state) {


        return <form onSubmit={this.submit} name="signup">
          <input pattern="/^\S*$/" type="text" name="firstName" value={this.state.firstName} onChange={this.handleChange} />
            <input pattern="/^\S*$/" type="text" name="lastName" value={this.state.lastName} onChange={this.handleChange} />
       

            <div class="s72-buttons">
                <button type="submit">submit</button>
            </div>
        </form>;
    }
}

Upvotes: 3

Related Questions