How to add dynamic validation in form using reactjs

Asked
Active3 hr before
Viewed126 times

10 Answers

validationreactjsusingdynamic
90%

Now, let's create our validator schema (which is just a plain javascript object) from the description above, and save it as /validators.js.,Custom validators in AngularJS - Includes more ideas on the topic of how AngularJS handles form validation,Creating a reusable component for your input elements where the validators for each input is passed as props.

Now, let's create our validator schema (which is just a plain javascript object) from the description above, and save it as /validators.js.

const validator = {
   username: {
      rules: [{
            test: /^[a-z0-9_]+$/,
            message: 'Username must contain only alphabets-numeric lowercase characters',
         },
         {
            test: (value) => {
               return value.length > 2;
            },
            message: 'Username must be longer than two characters',
         },
      ],
      errors: [],
      valid: false,
      state: '',
   },
   password: {
      rules: [{
         test: (value) => {
            return value.length >= 6;
         },
         message: 'Password must not be shorter than 6 characters',
      }, ],
      errors: [],
      valid: false,
      state: ''
   },
};

export default validator;
88%

React - Form Validation Example with React Hook Form , React + Formik Dynamic Form Example , React - CRUD Example with React Hook Form

0
72%

Thanks for contributing an answer to Stack Overflow!, Stack Overflow Public questions & answers ,I am using ant design in my demo application. I want to add dynamic validation of mobile number in my application.

You need to set rules as per some conditions like so:

 const rules = mobileValidation ?
    [{
          required: true,
          message: "Please input a number!"
       },
       {
          pattern: /^[2-9]{2}\d{8}$/,
          message: "Please input 10 digit number!"
       }
    ] :
    null;
load more v
65%

First we loop through each configuration in the configuration list,Clone the configuration which is the current scope on looping (as we don’t need to modify the configuration which is in the state),constants.FormValidations.js

constants.FormValidations.js

export const formValidationConfigList = [{
   apiName: 'name',
   dataType: 'text',
   id: 'name',
   isRequired: true,
   hasError: false,
   label: 'Name',
}, {
   apiName: 'startDate',
   dataType: 'date',
   id: 'startDate',
   isRequired: true,
   hasError: false,
   label: 'Start Date',
}, {
   apiName: 'endDate',
   dataType: 'date',
   id: 'endDate',
   isRequired: false,
   hasError: false,
   errorMessage: '',
   label: 'End Date',
   dependantAPIName: 'startDate;endDate',
   constraints: (modal) => {
      const hasError = modal.endDate && modal.startDate && (new Date(modal.endDate) < new Date(modal.startDate)) return {
         value: (hasError && '') || modal.endDate,
         variables: {
            errorMessage: (hasError && 'End date cannot be greater than Start date') || '',
            hasError,
         },
      }
   },
}, ]
load more v
75%

We loop through fields to get the placeholders and add them to the schema object. That is all you need to add dynamic fields for validation with Yup.,With Yup it is easy to loop through fields of an object and then add them to your validation schema, allowing you to validate form that does not have fixed fields.,To build the Yup schema, we first add the static fields to , from and subject for validation. Then we loop through the keys of the variable field of the response.data object and build the Yup form validation schema dynamically by removing the brackets then using each placeholder entry as a key.

Pretag
 Pretag team - issue, fix, solve, resolve
40%

Append form input fields.,Post Code Benefits, this post code will provide below things:,Getting form input fields data after form successfully submitted.

npx create - react - app reactjsappendfields

cd reactjsappendfields

npm start // run the project
load more v
22%

5Validate Custom React Component Props with PropTypes 3m 30s,10Use Component State with React 7m 9s,12Use Class Components with React 4m 16s

Thoughts on returning an empty div element when there is no error?

error ? <div style={{color: 'red'}}>{error}</div> : <div/>
load more v
60%

So let’s start with building the simplest form with React and Formik.,So we will see an example of adding custom validation to Yup. Yup provides us an addMethod interface to add our own user-defined validations in the application. ,Here is an example of custom method validation which takes Y and N as boolean values.

Pretag
 Pretag team - issue, fix, solve, resolve
48%

The example app component contains all the code for the dynamic form built with React Hook Form.,This is a quick example of how to build a dynamic form with validation in React with the React Hook Form library.,Check out the article about creating a contact form with React and PHP:

Pretag
 Pretag team - issue, fix, solve, resolve
23%

Dynamic form can be very useful and more economical to create the forms based on JSON data and without need for adding/changing any code.,For the dynamic forms, we can create a new React tsx called dynamic-form.tsx which is responsible for rendering a dynamic form based on the Json data.,The following example demonstrates how to create the sign up form dynamically.

export const data = {
   A_FirstName: {
      floatLabelType: 'Auto',
      key: 'FirstName',
      label: 'First Name',
      placeholder: 'First Name',
      type: 'text',
      validation: {
         required: true
      }
   },
   B_LastName: {
      floatLabelType: 'Auto',
      key: 'LastName',
      label: 'Last Name',
      placeholder: 'Last Name',
      type: 'text',
      validation: {
         required: true
      }
   },
   C_Email_ID: {
      floatLabelType: 'Auto',
      key: 'Email_ID',
      label: 'Mail ID',
      placeholder: 'Email',
      type: 'email',
      validation: {
         required: true
      }
   },
   D_Password: {
      floatLabelType: 'Auto',
      key: 'Password',
      label: 'Password',
      placeholder: 'Password',
      type: 'password',
      validation: {
         required: true
      }
   },
   E_DOB: {
      floatLabelType: 'Auto',
      key: 'DOB',
      label: 'DOB',
      placeholder: 'DOB',
      type: 'date',
      validation: {
         required: true
      },
      width: '250px'
   },
   F_Accept: {
      key: 'Accept',
      label: 'Accept terms and conditions',
      type: 'checkbox',
      validation: {
         required: true
      }
   },
   G_Submit: {
      key: 'Button',
      type: 'submit'
   },
}
load more v

Other "validation-reactjs" queries related to "How to add dynamic validation in form using reactjs"