# Superform Instance

Superform instances allow you to utilize useful methods and properties, enabling fine-grained control over your forms.

## Form Data Methods

### `getFormData()`

With the `getFormData()` method, you can retrieve form values as an object.&#x20;

#### Syntax

<pre class="language-javascript"><code class="lang-javascript"><strong>const formData = myForm.getFormData() 
</strong></code></pre>

#### Method

| Name          | Returns  | Description                           |
| ------------- | -------- | ------------------------------------- |
| `getFormData` | `Object` | Retrieves form values as an `object`. |

#### Usage example:

```javascript
window.SuperformAPI = window.SuperformAPI || [];
window.SuperformAPI.push(({ getForm, allForms }) => {
    const myForm = getForm("myForm");
    const formData = myForm.getFormData(); // Returns form data as an object
    console.log(formData); // {email: "name@example.com", ...}
});
```

***

## Step Lifecycle Methods

### `beforeStepChange(fn)`

With the `beforeStepChange` method, you can register a listener that will execute right before a step change. This is useful for performing actions like triggering events for analytics.

#### Syntax

```javascript
myForm.beforeStepChange((params) => {})
```

#### Params Object

The `params` object passed to the `beforeStepChange` callback function contains the following properties:

| Property    | Type     | Description                             |
| ----------- | -------- | --------------------------------------- |
| `data`      | `Object` | The current form data                   |
| `stepCount` | `number` | The current step index                  |
| `progress`  | `number` | The current progress percentage (0-100) |
| `scores`    | `Object` | Contains score data                     |

#### Usage example:

```javascript
window.SuperformAPI = window.SuperformAPI || [];
window.SuperformAPI.push(({ getForm, allForms }) => {
    const myForm = getForm("myForm");
    myForm.beforeStepChange((params) => {
        console.log(params.data); // Returns form data
        console.log(params.stepCount); // Returns current step index
        console.log(params.progress); // Returns current progress percentage
        console.log(params.scores); // Returns scores object

        // Sending custom event for analytics
        gtag("event", "step_event", {
            "step_index": params.stepCount,
            "progress": params.progress
        });
    });
});
```

### `onStepChange(fn)`

With the `onStepChange` method, you can register a listener that will execute on a step change. This is useful for performing actions like playing/pausing videos, playing animations, or storing user progress via third-party APIs.

#### Syntax

```javascript
myForm.onStepChange((params) => {})
```

#### Params Object

The `params` object passed to the `onStepChange` callback function contains the following properties:

| Property    | Type     | Description                             |
| ----------- | -------- | --------------------------------------- |
| `data`      | `Object` | The current form data                   |
| `stepCount` | `number` | The current step index                  |
| `progress`  | `number` | The current progress percentage (0-100) |
| `scores`    | `Object` | Contains score data                     |

#### Usage example:

```javascript
window.SuperformAPI = window.SuperformAPI || [];
window.SuperformAPI.push(({ getForm, allForms }) => {
    const myForm = getForm("myForm");
    const myVideo = document.getElementById("myVideo");

    myForm.onStepChange((params) => {
        console.log(params.data); // Returns form data
        console.log(params.stepCount); // Returns current step index
        console.log(params.progress); // Returns current progress percentage
        console.log(params.scores); // Returns scores object

        /**
        * Assuming a video element is present on the first step, 
        * auto-play when the user is on the first step. On step change, 
        * pause the video.
        **/
        if (params.stepCount === 0) {
            myVideo.play();
        } else {
            myVideo.pause();
        }
    });
});
```

***

## Form Submit Methods

### `onFormSubmit(fn)`

With the `onFormSubmit` method, you can register a listener that will execute when the form is submitted. This is useful for performing actions like triggering events for analytics or executing your business logic.

#### Syntax

```javascript
myForm.onFormSubmit((params) => {})
```

#### Params Object

The `params` object passed to the `onFormSubmit` callback function contains the following properties:

| Property    | Type     | Description                             |
| ----------- | -------- | --------------------------------------- |
| `data`      | `Object` | The current form data                   |
| `stepCount` | `number` | The current step index                  |
| `progress`  | `number` | The current progress percentage (0-100) |
| `scores`    | `Object` | Contains score data                     |

#### Usage example:

```javascript
window.SuperformAPI = window.SuperformAPI || [];
window.SuperformAPI.push(({ getForm, allForms }) => {
    const myForm = getForm("myForm");
    const myVideo = document.getElementById("myVideo");

    myForm.onFormSubmit((params) => {
        console.log(params.data); // Returns form data
        console.log(params.stepCount); // Returns current step index
        console.log(params.progress); // Returns current progress percentage
        console.log(params.scores); // Returns scores object

        // Sending custom event for analytics
        gtag("event", "lead_capture", {
            "interest": params.data.interest,
            "rating": params.scores.rating
        });
    });
});
```

***

## Hook Methods

### **`registerNavigationHook(hookName, fn)`**

Registers a custom navigation hook for form elements, enabling dynamic navigation logic based on form data or other conditions. Read more about navigation hooks [here](https://deltaclan.gitbook.io/superform/essentials/navigation-overview#hooks-navigation).

Navigation hooks support `async` returns, allowing you to return a promise that resolves to a string or number.

<table><thead><tr><th width="250">Parameter</th><th width="173">Type</th><th>Description</th></tr></thead><tbody><tr><td><code>hookName</code></td><td><code>string</code></td><td>A unique identifier for the hook.</td></tr><tr><td><code>fn</code></td><td><code>function</code></td><td>A function that executes for navigation. Receives a <code>params</code> object with form data and other details.</td></tr><tr><td><strong>Returns</strong></td><td></td><td>Returns either one valid instruction</td></tr><tr><td><code>step-name</code></td><td><code>string</code> or <code>Promise&#x3C;string></code></td><td>The callback function can return a Step Teleport by step name indicating the next step name.</td></tr><tr><td>Linear navigation instruction</td><td><code>"next"</code> <code>"prev"</code> <code>"previous"</code> <code>"back"</code> or <code>Promise&#x3C;Linear Instruction></code></td><td>The callback function can return a Linear navigation instruction.</td></tr><tr><td>Step Teleport by signed number instruction (i.e <code>+1</code>, <code>-2</code> or valid signed number)</td><td><code>Signed number as string</code> or <code>Promise&#x3C;Step teleport string></code></td><td>The callback function can return a Step Teleport by signed number navigation instruction.</td></tr><tr><td>Hook instruction (i.e <code>hook(another_Hook)</code>)</td><td><code>hook(HOOK_NAME)</code> or <code>Promise&#x3C;"hook(HOOK_NAME)"></code></td><td>The callback function can return a hook navigation instruction.</td></tr></tbody></table>

```javascript
// Wait for Superform to be ready before registering hooks
window.SuperformAPI = window.SuperformAPI || [];
window.SuperformAPI.push(({ getForm }) => {
    const myForm = getForm("myForm");

    // Register a navigation hook for conditional navigation
    myForm.registerNavigationHook("checkNavigation", (params) => {
        const { data, stepCount, progress, scores } = params;

        // Example condition for navigation
        if (data.bookingType === "Business") {
            return "business_step";
        } else {
            return "economy_step";
        }
    });
});

```

### `registerInputValidationHook(hookName, fn)`

Registers a custom validation hook for form inputs. This method allows you to define complex validation logic programmatically. Read more about validation hooks [here](https://deltaclan.gitbook.io/superform/input-validation-and-errors/validation/hook).

<table><thead><tr><th width="250">Parameter</th><th width="173">Type</th><th>Description</th></tr></thead><tbody><tr><td><code>hookName</code></td><td><code>string</code></td><td>A unique identifier for the hook.</td></tr><tr><td><code>fn</code></td><td><code>function</code></td><td>A function that executes for validation. Receives a <code>params</code> object with form data and other details.</td></tr><tr><td><strong>Returns</strong></td><td></td><td></td></tr><tr><td><code>true</code> or <code>false</code></td><td><code>Boolean</code></td><td>The callback function must return a <code>Boolean</code> indicating the validation result (<code>true</code> for pass, <code>false</code> for fail).</td></tr></tbody></table>

```javascript
// Wait for Superform to be ready before registering hooks
window.SuperformAPI = window.SuperformAPI || [];
window.SuperformAPI.push(({ getForm }) => {
    const myForm = getForm("myForm");

    // Register a validation hook for the email input field
    myForm.registerInputValidationHook("validateEmail", (params) => {
        const { data } = params; // Destructure to access form data directly
        return !data.email.includes("@gmail.com"); // Fail validation for Gmail addresses
    });
});

```

**Notes**

• The hook function must be synchronous; asynchronous operations should be managed outside this method.

• Using a unique hook name is crucial as reusing a hook name will overwrite the previous hook.
