Meta API

Meta API

To update the fields and form status from outside of the library, api's have been provided:

  • updateField
  • updateFormField
  • validateForm
  • destroy

How to update a simple form field

    // import `meta-api`
    import { metaAPI } from "mui-forms";
    // call the `updateFormField` method inside any update function
    metaAPI.metaForm.updateField(
        <Name of metaform>,
        <Field name>,
        <Field value>
    );

How to update a grouped form field

    // import `meta-api`
    import { metaAPI } from "mui-forms";
    // call the `updateFormField` method inside any update function
    metaAPI.metaForm.updateFormField(
        <Name of metaform>,
        <Form section name>,
        <Field name>,
        <Field value>
    );

How to validate a form

    // import `meta-api`
    import { metaAPI } from "mui-forms";
    // call the `validateForm` method to validate all fields
    const errorDetails = metaAPI.metaForm.validateForm(
        <Name of metaform>
    );
 
    // Check if form has errors
    if (errorDetails.hasErrors) {
        // Handle validation errors
        errorDetails.errors.forEach((error) => {
            console.log(`${error.id}: ${error.errorMsg}`);
        });
    } else {
        console.log("Form is valid!");
    }

Validate Form Return Structure

{
    hasErrors: boolean,  // true if validation errors exist
    errors: [
        {
            id: string,      // Format: <formName>.<fieldName>
            errorMsg: string // Validation error message
        }
    ]
}

Example Response

{
    "hasErrors": true,
    "errors": [
        {
            "id": "User Form.email",
            "errorMsg": "Please enter a valid email address"
        },
        {
            "id": "User Form.password",
            "errorMsg": "Password must be at least 8 characters long"
        }
    ]
}

Arguments

NameDescription
Name of metaformThis is the name of the mui-forms which must be given as an input property while using it. e.g.: <MuiForms name="Basic details" schema={schema} />.
Here the name is Basic details
Form section nameIn a grouped form, this is the name of parent section. For simple forms, it is not applicable
Field nameName of the field
Field valueValue of the field that we want to update the field with. Datatype can be String or Number or Boolean

Complete Example

For a complete working example of the validateForm API in action, check out the Validate Form Example showcasing how to validate a form and display validation errors.

Star us at github

© Copyright 2023 MuiForms