How to properly validate input values with React.JS?

前端 未结 9 1106
孤城傲影
孤城傲影 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:42

    You can use npm install --save redux-form

    Im writing a simple email and submit button form, which validates email and submits form. with redux-form, form by default runs event.preventDefault() on html onSubmit action.

    import React, {Component} from 'react';
    import {reduxForm} from 'redux-form';
    
    class LoginForm extends Component {
      onSubmit(props) {
        //do your submit stuff
      }
    
    
      render() {
        const {fields: {email}, handleSubmit} = this.props;
    
        return (
          
    {email.touched ? email.error : ''}
    ); } } function validation(values) { const errors = {}; const emailPattern = /(.+)@(.+){2,}\.(.+){2,}/; if (!emailPattern.test(values.email)) { errors.email = 'Enter a valid email'; } return errors; } LoginForm = reduxForm({ form: 'LoginForm', fields: ['email'], validate: validation }, null, null)(LoginForm); export default LoginForm;

提交回复
热议问题