skip to Main Content

I am new to React.
Trying to enforce min/max to Form.Control,
so min=0 max=1 step=0.01, it works on Up/Down arrows,
but what if user enters manually say 2.
It just accepts it, no errors, nothing.
Is there way to enforce that manual input validation,
so it basically doesn’t allow to enter 2?

Please help!

TIA,
Oleg.

2

Answers


  1. you can add validation in onChange function that before add in input check value:
    for example we can check the value ,if value larger than 1 , set 1 for input :

    import React, { useState } from "react";
    
    export default function Login() {
      const [state, setState] = useState<number>(0);
      const handleChangeInput = (e: React.ChangeEvent<HTMLInputElement>) => {
        const { value } = e.target;
        if (value && +value > 1) return setState(1);
    
        setState(+value);
      };
      return (
        <div style={{ padding: "40px" }}>
          <input
            type="number"
            onChange={handleChangeInput}
            value={state}
            min={0}
            max={1}
            step={0.1}
          />
        </div>
      );
    }
    

    if you don’t want to add state, and use from Formik or react-hook-form , you can validation for number such as blew for react-hook-form :

    <input
        {...register("fromAmount", {
            valueAsNumber: true,
            min: 5,
            max: price.data
                ? price.data.from.max
                : Infinity,
        })}
        type="number"
    />
    

    in this way user can write greater than 1 ( for example 2) on input but can’t submit form.

    Login or Signup to reply.
  2. If you want to enforce an user to do not enforce the input through UI, add min/max, if you want to enforce with validation you can add a "value" and an "onChange" attribute. The value attribute will handle the value and the onChange update the value (unless it doesn’t pass your validation).

    You can try it by yourself in the example I made on playcode.io.

    import React from 'react';
    import {useState} from 'react'
    
    export function App(props) {
      const [inputValue, setInputValue] = useState(0);
    
      const handleChange = (e) => {
        const inputValue = parseFloat(e.target.inputValue);
    
        if (!isNaN(inputValue) && inputValue >= 0 && inputValue <= 1) {
          setInputValue(inputValue);
        }
      };
    
      return (
        <div className='App'>
          <input
            type="number"
            value={inputValue}
            onChange={handleChange}
            min={0}
            max={1}
            step={0.01}
          />
        </div>
      );
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search