user12263110
user12263110

Reputation:

ReactJS Dynamic Form Validation with Material UI

I am going through the trouble to validate a form. My Form is given below which is minimal reproduce able.

I have used React Material UI for the form.

import React from 'react';
import TextField from '@material-ui/core/TextField';
import { FormGroup } from '@material-ui/core';

function App(props) {
  const validator = {
    number: {
      rules: [
        {
          test: /([\d]+)/,
          message: 'numaric must contain only numeric characters',
        },
        {
          test: (value) => {
            return value.length > 5;
          },
          message: 'phone must be longer than five characters',
        },
      ],
      errors: [],
      valid: false,
      state: '',
    },
  };

  const [values, setValues] = React.useState({
    ssn: '',
    phone: '',
    email: '',
    country: '',
  });



  const handleChange = name => event => {
    setValues({ ...values, [name]: event.target.value });
  };

return (
  <React.Fragment>
  <div>
    <FormGroup autoComplete="on">
      <TextField
        id=""
        label="Phone"
        value={values.phone}
        onChange={handleChange('phone')}
        type="number"
        validators={validator}
        name='phone'
      />
    </FormGroup> 
  </div>
  </React.Fragment>

  );
}

export default App;

I want if the user inserts values less than 5, they will get an error message, and if they don't insert numbers, they will get another error message.

I am going through the trouble to implement this simple validation

I need help, it will be much appropriated if anyone can help me in this case.

I have already written a validator with regex but I don't know how to implement this to show the error message.

Can anyone help me, please?

Upvotes: 2

Views: 4063

Answers (2)

KARTHIKEYAN.A
KARTHIKEYAN.A

Reputation: 20080

We can Validate array of form values in the following way

const rows = [
{
    "checked": false,
    "data": {
        "requestType": "Tom",
        "accountName": "",
    },
    "formDesc": {
        "accountName": {
            "field_label": "MF/Sub Account Name",
            "field_name": "accountName",
            "is_editable": "Y",
            "is_mandatory": "Y"
        },
        "address1": {
            "field_label": "RequestType",
            "field_name": "requestType",
            "is_editable": "Y",
            "is_mandatory": "N"
        }
    },
    "isCollapsed": false,
    "validationErrors": [ ]
}
]

const validate = rows => {
    let isValid = true
    const validatedRows = rows.map(row => {
        const validationErrors = []
        const formDesc = row.formDesc
        for (const r in formDesc) {
            if (formDesc[r].is_mandatory === 'Y' && !row.data[r]) {
                isValid = false
                validationErrors.push({
                    errorMessage: `${formDesc[r].field_label} is required`,
                    field: r
                })
            }
        }
        const rowWithValidation = {
            ...row,
            validationErrors: validationErrors,
        }
        return rowWithValidation
    })
    return { isValid, validatedRows }
}

console.log(validate(rows))

Upvotes: 0

Rakshith
Rakshith

Reputation: 11

I had a similar case where I need to test if the textfield is null. I did in the below manner in material-ui. You have error and helpertext which can do the validation and show the respective message.

material-ui text-field validation

<TextField
    required
    id="flowName"
    name="name"
    label="Flow Name"
    variant="outlined"
    value={name}
    error={name !== ""}
    helperText={name !== "" ? "Required!" : " "}
/>

And to check phoneNumber length change

error={values.phone.length < 5}
helperText={values.phone.length < 5 ? "Phone must be longer than five characters!" : " "}

Upvotes: 1

Related Questions