Neeraj Prajapati
Neeraj Prajapati

Reputation: 541

How to set input alphanumeric value format in input field reactjs?

I'm using reactjs in my project and want to set fixed format in input field that user can be enter only useful info. I already tried with react number format and try make custom but didn't get solution. so anybody help me for set format in input field like "ABCD-123EF".. means alphanumeric with dash and this is fix format. My code is:

<Input
      type="text"
      id="plate_number"
      name="plate_number"
      placeholder="Licence Plate"
      value={this.state.plate_number}
      onChange={this.onChangeHandle}
/>  

enter image description here

Upvotes: 1

Views: 10643

Answers (2)

Patrick Otto
Patrick Otto

Reputation: 181

See my solution:

export const inputAlphaNumeric = (e, callback) => {

    const value = (e.target.value) ? e.target.value.replace(/[^0-9a-zA-Z]+/ig, "") : '';

    if (e.target.value !== value) {
        e.target.value = value;
    }

    if(typeof callback === 'function'){
        return callback(value);
    }
}

Add function in onChange input parameter:

<Form.Group>
    <Form.Label>Example</Form.Label>
    <Form.Control 
        type="text"
        defaultValue={""}
        onChange={(e) => inputAlphaNumeric(e, (value) => {
            // customize with your code
            this.setState({ custom: value  });
        })}
     />
</Form.Group>

Result:

enter image description here

Upvotes: 1

MaCadiz
MaCadiz

Reputation: 1817

You can always use Regex to evaluate the incoming string like this.

onChangeAlphaNumericInput(e) {
  const value = e.target.value;
  const regex = /^[0-9a-zA-Z(\-)]+$/; //this will admit letters, numbers and dashes
  if (value.match(regex) || value === "") {
    this.setState({ inputValue: value });
  }
}

This will let your input to prevent to write any unwanted special character.

EDIT:

onBlur validation for that field

onBlurValidateFormat(e) {
  const value = e.target.value;
  const regex = /([a-zA-Z]{4})+-([0-9]{3})+([a-zA-Z]{2})+$/g;
  if (!value.match(regex)) {
    //Show an error message or put a warning text under the input and set flag to prevent form submit
  }
}

Upvotes: 0

Related Questions