2

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?

4
  • I think the material-ui TextField component doesn't have validators property. You might want to check redux-form or formik to easily handle your forms in case you have multiple fields in you app. Commented Oct 23, 2019 at 13:11
  • How can i do it? Commented Oct 23, 2019 at 13:17
  • if you prefer to use formik. A good article with example integration with material-ui medium.com/codefully-io/…. Otherwise, you can always read the documentation here: jaredpalmer.com/formik/docs/api/formik Commented Oct 23, 2019 at 13:21
  • I think Formik is especially good at dynamic forms that have a flat model (like your example). For dynamic forms that support complex models I published an experimental solution that’s working well for me npmjs.com/package/leaf-validator This declaratively operates immutable state progression and bases the shape of the validation model on the shape of the data model. Immutable and declarative are often great solutions especially in React. Here is an example codesandbox.io/s/…: Commented Feb 26, 2020 at 4:14

2 Answers 2

1

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!" : " "}
Sign up to request clarification or add additional context in comments.

Comments

0

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))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.