How to properly validate input values with React.JS?

前端 未结 9 1116
孤城傲影
孤城傲影 2020-12-22 19:07

I have a simple form. All of the components and state are held in the Page component. There are 2 display headers and 3 input fields. The first input is supposed to be text,

9条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-22 19:58

    I have used redux-form and formik in the past, and recently React introduced Hook, and i have built a custom hook for it. Please check it out and see if it make your form validation much easier.

    Github: https://github.com/bluebill1049/react-hook-form

    Website: http://react-hook-form.now.sh

    with this approach, you are no longer doing controlled input too.

    example below:

    import React from 'react'
    import useForm from 'react-hook-form'
    
    function App() {
      const { register, handleSubmit, errors } = useForm() // initialise the hook
      const onSubmit = (data) => { console.log(data) } // callback when validation pass
    
      return (
        
    {/* register an input */} {/* apply required validation */} {errors.lastname && 'Last name is required.'} {/* error message */} {/* apply a Refex validation */} {errors.age && 'Please enter number for age.'} {/* error message */}
    ) }

提交回复
热议问题