数据验证后提交表单

时间:2018-05-29 11:40:14

标签: forms reactjs validation redux jsx

我使用React和Redux创建了表单并进行了验证。 验证的条件:

  • 数据应在输入时验证
  • 数据应在提交前再次验证
  • 所有数据都是强制性的,数据有效

当用户开始输入数据时,我检查数据并在使用发送输入到商店时发送它们。 当用户首先点击“提交”按钮时,我检查数据是否有价值,并将状态发送到商店。

问题:

如果在提交时所有数据都有有效值,我是否需要再次将数据发送到商店?

我的操作 ./ actions / index.js

export const changeValue = (field, value, isValid) => ({
type: "CHANGE_VALUE",
  value, isValid, field
})

我的reducer ./ reducers / form.js

const form = (state={
 firstName: {isValid: true, value: ''},
 mail: { isValid: true, value: ''}
 }, action) => {
  switch (action.type) {
    case 'CHANGE_VALUE':
      state[action.field].isValid = action.isValid
      state[action.field].value = action.value
      const user = Object.assign({}, state)
      return user
    default:
      return state
  }
}
export default form

我的容器格式为 ./ containers / Form.js ::

import React from 'react'
import { connect } from 'react-redux'
import { changeValue } from '../actions'

const hasOnlyLetters = value => value.match(/^[a-zA-Z]+$/)
const re  = /^[A-Z0-9._%+-]+@([A-Z0-9-]+\.)+[A-Z]{2,4}$/i
const hasEmail = value => value.match(re)

const Form = ({ dispatch, inputs }) => {

  // Check the data at the time of the data input
  const changeHandler = (isValid, field, e) => {
    const { value } = e.target
    if (isValid(value)){
      dispatch(changeValue(field, value, true))
    } else {
      dispatch(changeValue(field, value, false))
    }
  }

  // Check the data before submission
  const handleSubmit = (e) => {
    e.preventDefault()
    if (!inputs.firstName.value) {
      dispatch(changeValue('firstName', inputs.firstName.value, false))
    }
    if (!inputs.mail.value) {
      dispatch(changeValue('mail', inputs.lastName.value, false))
    }
    if(!inputs.firstName.isValid || !inputs.mail.isValid) {
      return alert('error')
    } else {
     // Send the data to the store again?
      return alert('success')
    }  
  }


  const error = (field, type) => {
    if (!field.value && !field.isValid) {
      return <span>Field is required</span>
    } else if (field.value && !field.isValid && type === "text") {
      return <span>Should contain only letters</span>
    } else if (field.value && !field.isValid && type === "mail") {
      return <span>Value should be a valid email</span>
    } else{
      null
    }
  }

  return (
    <div>
      <form onSubmit={handleSubmit}>
        <div>
        <label>First name:</label>
        <input type="text" value={inputs.firstName.value} onChange={changeHandler.bind(null, hasOnlyLetters, 'firstName')}/>
        { error(inputs.firstName, "text") }
        </div>
         <div>
        <label>Email:</label>
        <input type="mail" value={inputs.mail.value} onChange={changeHandler.bind(null, hasEmail, 'mail')}/>
        { error(inputs.mail, "mail") }
        </div>
        <button type="submit">
          Add Todo
        </button>
      </form>
    </div>
  )
}


function mapStateToProps(state) {
  return { inputs: state.form }
}
export default connect(mapStateToProps)(Form)

1 个答案:

答案 0 :(得分:0)

我建议您先在状态中设置值并执行验证。在组件中验证后,您可以在商店中设置正确的值。

`export default class Form extends React.Component{

     constructor(props){
         super(props);
         this.state={
             name:'';
             age:''
         }
     }

     handleSubmit=()=>{
         if(this.state.name===''){
             perform validation
         }
         else if(this.state.name===''){

         }//other validation(s)
         else 
         {
             //set data in store only when the fields are correct..
         }
     }

     render(){
         return (<div>
             <input type="text" onChange={(event)=> 
                 {this.setState({name:event.target.value})}} />
             <input type="number" onChange={(event)=> 
                 {this.setState({age:event.target.value})}} />
             <button onClick={this.handleSubmit}>Submit</button>
        </div>)
     }
 }`

这将有助于您只拥有商店中经过验证的数据。