Home > OS >  How to properly control data input?
How to properly control data input?

Time:10-07

There is a task to supervise input in . It is necessary to give the ability to enter only strings of numbers ([0-9]) into the entity input. At the same time, if something else is entered, then do not overwrite value and do not display incorrect input in the input. I can't find a solution for my case. Validity check ( target.validity.valid ) didn't work either because I have control over the minimum and maximum lengths. At the same time, I have a universal function for several inputs, but only the entity needs to be checked. Please tell me how to correctly implement the check for input [0-9] and so that nothing else can be entered.

The examples that are on the resource are not suitable because they do not take into account the control of the minimum-maximum length

Below is a shortened code example

const [inputState, setInputState] = useState({title : "", entity: ""})

  const handleChangeInputValue = (event) => {
    const { target } = event;
    const { name, value } = target;
    // Need to check for numbers
    setInputState({ ...inputState, [name]: value });
  };


              <input
                required
                minLength={5}
                type="text"
                placeholder="Enter name"
                name="title"
                value={inputState.title}
                onChange={handleChangeInputValue}
              />
              <input
                required
                minLength={13}
                maxLength={15}
              
                type="text"
                placeholder="Enter entity"
                name="entity"
                value={inputState.entity}
                onChange={handleChangeInputValue}
              />

CodePudding user response:

you can use HTML 5

<input type="number" name="someid" />

This will work only in HTML5 complaint browser. Make sure your html document's doctype is:

<!DOCTYPE html>

CodePudding user response:

if(name==='entity' && !value.match(/^\d $/)) { 
return
 }
  • Related