As a continuation of the previous part, we are going to implement React form validation and to create a new owner entity by sending a POST request towards our .NET Core Web API server.

In the CreateOwner component, we pass the handleChangeEvent() function to the Input component. We are going to use this function to enable two-way binding and to validate our input fields. Therefore, the implementation and sending POST request is what we aim for in this post.

If you want to see all the basic instructions and complete navigation for the .NET Core series, check out the following link: Introduction to the .NET Core series.

For the complete navigation and all the basic instructions of the React series, check out: Introduction to the React series.

For the previous part check out: Dynamic Form Configuration

The source code is available at GitHub: React series – react-series-part7-end branch

This post is divided into several sections:

Handling OnChange Event with the handleChangeEvent Function

Right now if we type something inside the input fields nothing is going to happen. That is because, in our InputConfiguration.js file all “value” properties are set to empty strings for all the inputs (except for the datePicker, it accepts the moment() function which always applies the current date). More important is that we never change the value property inside the configuration object, thus the empty input fields.

We are going to fix this and to add a validation, by implementing the handleChangeEvent function.

Let’s modify the CreateOwner.js file by adding the handleChangeEvent function below the componentWillMount lifecycle hook:

handleChangeEvent = (event, id) => {
    const updatedOwnerForm = { ...this.state.ownerForm };
    updatedOwnerForm[id] = formUtilityActions.executeValidationAndReturnFormElement(event, updatedOwnerForm, id);

    const counter = formUtilityActions.countInvalidElements(updatedOwnerForm);

    this.setState({ ownerForm: updatedOwnerForm, isFormValid: counter === 0 })

This function accepts two parameters. The event parameter that holds the value from our input fields (not only the value but this one is important for us) and the id parameter to which we are going to pass one of the configuration object keys (name, address or dateOfBirth).

We are deeply cloning the ownerForm from the state, and then updating the configuration of the currently modified input by calling the executeValidationAndReturnFormElement function. After the validation, we are counting how many fields are invalid, and if any, our complete form is going to be marked as invalid. Finally, we are going to update the state.

Creating Additional Functions for React Form Validation

We have executeValidationAndReturnFormElement and countInvalidElements functions but they are not created yet.

So, let’s create them.

Let’s modify the FormUtility.js file:

export const executeValidationAndReturnFormElement = (event, updatedOwnerForm, id) => {
    let formElement = { ...updatedOwnerForm[id] };
    formElement.value = id === 'dateOfBirth' ? event :;
    formElement.touched = true;

    const validationResponse = checkValidity(formElement.value, formElement.validation);

    formElement.valid = validationResponse.isValid;
    formElement.errorMessage = validationResponse.errorMessage;

    return formElement;

First, we are cloning the exact formElement which user currently modifies. Then populate the formElement‘s value by using a ternary operator (If a user modifies the dateOfBirth input, then the event is the value. But for any other input field, the event is the object that has the target property which holds the value property). Furthermore, we are going to set our control to touched and then send the value and the validation rules to the validation process. Once the process is done we store those results. Finally, we return formElement with all the changes.

Implementing the CheckValidity Function

So, let’s implement the checkValidity function just above the executeValidationAndReturnFormElement function:

const checkValidity = (value, validation) => {
    let validationObject = {
        isValid: true,
        errorMessage: ''

    if (validation) {
        if (validation.required) {
            validationObject.isValid = value.trim() !== '';
            validationObject.errorMessage = validationObject.isValid ? '' : 'Field is required';

        if (validationObject.isValid && validation.maxLength) {
            validationObject.isValid = value.length <= 60;
            validationObject.errorMessage = 'Not allowed more than 60 charactes';

        return validationObject;
    else {
        return validationObject;

With the code above we check if we need to validate the input at all. If it needs to be validated then we perform validation but if it doesn’t (like dateOfBirth) we just return the same object back.

In the validation process, we check does the field have the required validation rule and validate it. Then if it is still valid we validate against the maxLength rule. Finally, we just return the validationObject.

Entire React Form Validation

Inside the handleChangeEvent function, we are calling one additional function the countInvalidElements. So let’s implement that one just below the executeValidationAndReturnFormElement function in the FormUtility.js file:

export const countInvalidElements = (ownerForm) => {
    let countInvalidElements = 0;
    for (let element in ownerForm) {
        if (!ownerForm[element].valid) {
            countInvalidElements = countInvalidElements + 1;
    return countInvalidElements;

This function is pretty straightforward. We loop through all the elements inside the ownerForm. And if we find any element which is invalid, we just increase the countInvalidElements variable and leave the loop. Finally, we return that variable.


Now we can inspect the results.

Empty form (that has never been touched):

Empty Form React Form Validation

If we place our cursor inside our input fields and leave:

Touched Form React Form Validation

Another type of error message:

React Form Validation Max Character Length

Finally, the valid form:

Create Form Valid React Form Validation

Connect the CreateOwner Component With the Reducer

First, let’s add all the necessary imports:

import { connect } from 'react-redux';
import * as repositoryActions from '../../../store/actions/repositoryActions';
import * as errorHandlerActions from '../../../store/actions/errorHandlerActions';

Next, let’s create mapStateToProps function below the component:
const mapStateToProps = (state) => {
    return {
        showSuccessModal: state.repository.showSuccessModal,
        showErrorModal: state.errorHandler.showErrorModal,
        errorMessage: state.errorHandler.errorMessage

After that, we need to create mapDispatchToProps function below the mapStateToProps:
const mapDispatchToProps = (dispatch) => {
    return {
        onCreateOwner: (url, owner, props) => dispatch(repositoryActions.postData(url, owner, props)),
        onCloseSuccessModal: (url, props) => dispatch(repositoryActions.closeSuccessModal(props, url)),
        onCloseErrorModal: () => dispatch(errorHandlerActions.closeErrorModal())

Then, let’s modify the export statement:
export default connect(mapStateToProps, mapDispatchToProps)(CreateOwner);

Finally, we are going to add our modal components below the FormGroup tag but still inside the Well tag:
<SuccessModal show={this.props.showSuccessModal} 
       modalHeaderText={'Success message'} 
       modalBodyText={'Action completed successfully'}
       successClick={() => this.props.onCloseSuccessModal('/owner-List', { ...this.props })} />

<ErrorModal show={this.props.showErrorModal} 
        modalHeaderText={'Error message'} 
        okButtonText={'OK'} closeModal={() => this.props.onCloseErrorModal()} />

And, add the import statements:
import SuccessModal from '../../../components/Modals/SuccessModal/SuccessModal';
import ErrorModal from '../../../components/Modals/ErrorModal/ErrorModal';

The SuccessModal is calling the onCloseSuccessModal property from the mapDispatchToProps function. Moreover, the ErrorModal is calling the onCloseErrorModal property from the mapDispatchToProps function. Both of those properties are dispatching functions which are not implemented. So this is something we need to fix.

Modifying the Action and the Reducer files

We need to modify our files by adding additional functions for closing success and error modal components.

Let’s add two more action types inside the ActionTypes.js file:


Then let’s modify the repositoryActions.js file by adding the closeSuccessModal function:
export const closeSuccessModal = (props, url) =>{
    return {
        type: actionTypes.CLOSE_SUCCESS_MODAL,
        props: props,
        url: url

We need to modify the repositoryReducer.js file as well:
case actionTypes.CLOSE_SUCCESS_MODAL:
            return executeCloseSuccessModal(state, action)

const executeCloseSuccessModal = (state, action) => {
    return {
        showSuccessModal: false

We are done with the success modal, let’s do the similar thing for the error modal.

First, let’s modify the errorHandlerActions.js file by adding a new function:

export const closeErrorModal = () => {
    return {
        type: actionTypes.CLOSE_ERROR_MODAL

Then, let’s modify the errorHandlerReducer.js file:
case actionTypes.CLOSE_ERROR_MODAL:
            return executeCloseErrorModal(state, action);

const executeCloseErrorModal = (state, action) => {
        showErrorModal: false,
        errorMessage: ''

Now, all we have to do is to send a POST request from the CreateOwner component.

Handling POST Request

There is onSubmit event inside the Form tag, which points to the createOwner function. Let’s implement that function below the handleChangeEvent function:

createOwner = (event) => {

    const ownerToCreate = {
        address: this.state.ownerForm.address.value,
        dateOfBirth: this.state.ownerForm.dateOfBirth.value

    const url = '/api/owner';
    this.props.onCreateOwner(url, ownerToCreate, { ...this.props });

Below this function we need to add one more function for the Cancel button functionality:
redirectToOwnerList = () => {

Now we can check out the results:

Success modal window

If the error occurs, with the status code other than 404 or 500:

error modal bad request


By reading this post you have learned:

  • How to handle the onChange event in an input field
  • To validate our dynamically created form
  • How to use previously created modal window components
  • The way to handle POST request

Thank you for reading the article and I hope you found something useful in it.

In the next part of the series, we are going to learn how to handle PUT requests. Furthermore, we are going to use different lifecycle hooks in React and learn how to update our state with the modified data from the server.