1

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

3
  • You can look around this package which allows you to apply a regular expression on your input data. Commented May 21, 2020 at 4:11
  • @ⵍⵢⴻⵙ if possible then can you set format like above required? Commented May 21, 2020 at 4:37
  • You'll need to a regex like ^\w{4}-\w{4}$ or ^[a-zA-Z0-9]{4}-[a-zA-Z0-9]{4}$ if you don't accept special characters Commented May 21, 2020 at 4:51

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

Comments

0

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
  }
}

1 Comment

Well, in that case. I recomend to validate the format in an onBlur event. I'll update my answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.