简体   繁体   中英

Validate form in React js

I'm trying to validate form onSubmit in my React Application.

This is one of the components which is rendered in main file. This components is called by click on set alarm button. This is not that important,but what is,I'm sending getInfo() function from main component to this component as a prop. I need to call this function when validation returns true

Form consists of 3 input fields and one button,but I don't need to check the first one.

Since my application is Alarm clock,and this form pops up when you click Set alarm button, I need to check if

  • First input is not empty and if it's value is not over 24 (in this input you set hours for alarm)
  • Second input is not empty and if it's value is not over 60 (in this input you set minutes for alarm)

My idea was to create States for these values and create functions which are supposed to update states. Functions are called onChange that specific input.

const [validate,setValidate] = useState({
    message:'',
    hours:'',
    minutes:''
}) 

function updateHours(e){
    let value = e.target.value
    setValidate(prevState => ({
        ...prevState,
       hours:value
    }))
}

function updateMinutes(e){
    let value = e.target.value;
    setValidate(prevState => ({
        ...prevState,
        minutes:value
    }))
}

To this point everything works fine. Then I've tried to create new function which will be validating these values and should return the result. This function will be called onSubmit ,and if returns true,it means everything is okay and form will be send.

let getInfo = props.getInfo;

function validateForm(){
    if(validate.hours > 24){
        alert('enter correct hours !')
        return false;
    }

    if(validate.minutes > 60){
        alert('enter correct minutes !')
        return false;
    }

    return getInfo;
}

I've tried to Google it how to do this onSubmit and all I can find was this approach,which did not work. It behaves like no function is called.

<form onSubmit="return validateForm">
     <FontAwesomeIcon 
        icon={faTimesCircle} 
        className="closeIcon"
        onClick={() => setAlarm(false)} />

     <h3>Please set your alarm</h3>

     <label htmlFor="text">Message</label>
     <input type="text" id="text" autoComplete="off" autoFocus="on" />

     <div className="flex">
       <div className="inputNumber">
          <label htmlFor="hours">Hour</label>
          <input type="number" id="hours" name="hours" onChange={updateHours} />
       </div>
                                
       <div className="inputNumber">
          <label htmlFor="minutes">Minute</label>
          <input type="number" id="minutes" name="minutes" onChange={updateMinutes} />
       </div>
    </div>
    <button onClick={()=>setAlarm(false)}>SET ALARM</button>
</form>

Has anyone encountered this kind of problem or can you give me advice what to do with it? Also I'm open-minded to some better approach for this. Thank you.

First of all I should say that it is not neessary to make validation in web platform by yourself since the browser validated everything itself. See Constraint Validation API . And I know that feels strange since most of the developers do it themselves. I do not see any necessity though.

What you have to do is constraint the values, but not validate, with various attributes accoring to your needs; type, pattern, min, max, minlength, maxlength, required etc.

You will be equipped by some properties ( validity etc.), methods ( checkValidity etc.), attributes ( type , pattern , min , max etc.), pseudo classes ( :invalid , :valid etc.), and events ( invalid etc.) that you will need if the user input is valid with respect to your constraints.

Using these you will have the reason why, and when it is invalid, and opportunities to set a custom invalid state message or style. By the way It does not matter if you use a framework like React or anything else, it is still there to use.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM