redux form server side validation

ぐ巨炮叔叔 提交于 2020-05-17 08:23:46

问题


I am stuck in setting the server-side validation of the redux form. I have a registration form and performing a client-side validation perfectly, but while in server-side validation I am unable to understand how to display the error message from the server with a respective input field.

API request

 const createMemberRegistration = user => {
  return dispatch => {
  dispatch({ type: POST_REQUEST });
   processMemberRegistration(user)
   .then(user => {
    dispatch({ type: REGISTRATION_SUCCESS });
    dispatch(reset('memberregistration'));
  })
  .catch(err => {
    dispatch({ type: REGISTRATION_ERROR,payload:err });
  });
  };
 };

Component

 // submit button
 submitSignup(values) {
  var registerfields = JSON.stringify({
   first_name: values.firstname.trim(),
   last_name: values.lastname.trim(),
   email: values.email.trim(),
   password: values.password.trim()
 });
 if (registerfields) {
  this.props.createMemberRegistration(registerfields);
 }
}

//binding with redux form
const reduxmemberregistration = reduxForm({
 form: "memberregistration",
 validate:isvalidMemberRegistration,
 asyncValidate,
 enableReinitialize: true
})(MemberRegistration);

Asycn function

stuck here what to do and how to validate with respective field

 const asyncValidate = (values, dispatch, props) => {
  return new Promise((resolve, reject) => {
   if(values.email){ // i get the value from the form,so what to do here?
    // so should i need to send request all the time to server for each 
      field for validation or what?
  }
 }
});
};

回答1:


Let's say you have a object that represents the state of you form and there you have some error property with same properties as fields on your form.

Let's say it looks like this

formState: {name : 'Test', error: {name: null} }

And you are rendering some error message under your inputs or decorating invalid input field with some class based on this formState.error.name.

In this situation you may get response object from server that also bears some input specific information and store it in e.g. formState.serverError error. So once data is fetched from backend you will post an action with this validation to Redux store, and if there are some errors, you will populate corresponding errors and will show appropriate error messages.

Condition for input field validity now will look like formState.error.name && formState.serverError.name



来源:https://stackoverflow.com/questions/48277215/redux-form-server-side-validation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!