> ## Documentation Index
> Fetch the complete documentation index at: https://formcarry.com/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Server-Side Field Validation Rules

> Enforce validation rules on your form fields in formcarry — require fields, validate email format, URL format, and more.

formcarry provides server-side field validations so you can enforce data quality rules without writing any backend code.

Rules are configured per field in your form's Settings, and formcarry evaluates every incoming submission against them automatically.

When a submission fails validation, formcarry returns an HTTP `422` response with a structured error object that tells you exactly which fields failed and why.

## Available Validators

| Validator     | Description                                |
| ------------- | ------------------------------------------ |
| `Required`    | Field cannot be empty                      |
| `Number`      | Field must be a number                     |
| `Email`       | Field must be a valid email address        |
| `Url`         | Field must be a valid URL                  |
| `Contains`    | Field must contain the specified value     |
| `NotContains` | Field must not contain the specified value |

***

## Validation Error Response

When one or more validation rules fail, formcarry responds with HTTP **422** and a JSON body:

```json theme={null}
{
  "code": 422,
  "status": "error",
  "title": "Validation Failed",
  "message": "The email must be a valid email address. (+1 more errors)",
  "errors": {
    "email": {
      "message": "The email must be a valid email address.",
      "rule": "email"
    },
    "name": {
      "message": "The name field is mandatory.",
      "rule": "required"
    }
  }
}
```

The `errors` object is keyed by field name, making it straightforward to map each error back to the corresponding input in your form.

***

## Displaying Errors in Your Form

You can use the `form-error` CSS class (or any class of your choosing) to visually highlight inputs that failed validation. The following examples show how to parse the `errors` object and apply the class to the matching form elements.

<CodeGroup>
  ```javascript Fetch theme={null}
  document.querySelector('.ajaxForm').addEventListener('submit', function (e) {
    e.preventDefault();

    fetch('https://formcarry.com/s/yourFormId', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Accept': 'application/json',
      },
      body: JSON.stringify({ email: 'wrongEmail', name: '' }),
    })
      .then((response) => response.json())
      .then((response) => {
        if (response.code === 422) {
          var errors = response.errors;
          for (var key in errors) {
            if (errors.hasOwnProperty(key)) {
              var formElement = document.querySelector('[name="' + key + '"]');
              if (formElement) {
                formElement.classList.add('form-error');
              }
            }
          }
          alert('An error occurred: ' + response.message);
        } else {
          alert('We received your submission, thank you!');
        }
      })
      .catch((error) => console.log(error));
  });
  ```

  ```javascript jQuery theme={null}
  $(function () {
    $('.ajaxForm').submit(function (e) {
      e.preventDefault();
      var href = $(this).attr('action');

      $.ajax({
        type: 'POST',
        dataType: 'json',
        url: href,
        data: $(this).serialize(),
        success: function (response) {
          if (response.code === 422) {
            $.each(response.errors, function (key) {
              $('[name="' + key + '"]').addClass('form-error');
            });
            alert('An error occurred: ' + response.message);
          } else {
            alert('We received your submission, thank you!');
          }
        },
      });
    });
  });
  ```
</CodeGroup>

### Styling Error Inputs

Add a CSS rule for `.form-error` to give users a clear visual signal that a field needs attention:

```css theme={null}
.form-error {
  border: 2px solid red;
  background-color: #ffe6e6;
}
```

This adds a red border and a light red background to any input that failed validation. Adjust the colors and properties to match your site's design.
