# Validators Reference

Complete reference for all No.JS form validators supported by the LSP. Data sourced from `server/src/data/validators.json`.

**6 `validate` rules** (`required`, `email`, `url`, `min`, `max`, `custom`) for declarative form validation, plus the native constraint attributes that `validate` also checks (`minlength`, `maxlength`, `pattern`, `step`, ...). Validation runs in the `@no-js-dev/nojs-elements` plugin.

Validators are pipe-separated rules applied to form elements via the `validate` attribute:

```html
<input name="email" validate="required|email" />
```

Rules with arguments use a colon separator:

```html
<input name="age" validate="required|min:18|max:120" />
```

Per-field error messages use `error-<rule>` companion attributes:

```html
<input name="email"
       validate="required|email"
       error-required="Email is required"
       error-email="Enter a valid email address" />
```

See also: [Completions](../features/completions.md) · [validate directive](../reference/directives.md#validate)

---

## Master Table

| Name | Description | Arguments | Example |
|------|-------------|-----------|---------|
| `required` | Field must not be empty | — | `validate="required"` |
| `email` | Field must be a valid email address | — | `validate="email"` |
| `url` | Field must be a valid URL | — | `validate="url"` |
| `min` | Minimum numeric value | `value` (number) | `validate="min:5"` |
| `max` | Maximum numeric value | `value` (number) | `validate="max:100"` |
| `custom` | Runs a validator registered with `NoJS.validator()` | `name` (string) | `validate="custom:phone"` |

`email` passes an empty value. By default `url`, `min` and `max` also check an empty value: `min` and `max` compare it as `0` and `url` fails `""`. See [Empty Values](#empty-values-validate-empty).

### Native constraint attributes

These are HTML attributes, not `validate` rules: `validate` checks them through the browser's `ValidityState` and reports them under their own names, so `error-<name>` works. Writing them as rules (`validate="minlength:3"`) does nothing, and the LSP reports it.

| Attribute | Description | Example |
|-----------|-------------|---------|
| `required` | Value must not be empty | `required` |
| `minlength` | Minimum string length | `minlength="3"` |
| `maxlength` | Maximum string length | `maxlength="50"` |
| `pattern` | Regex the value must match | `pattern="[A-Za-z]+"` |
| `min` / `max` | Numeric or date range | `min="1"` |
| `step` | Numeric step constraint | `step="0.01"` |
| `type` | `email`, `url`, `number`, `date`, ... | `type="email"` |

---

## Validators

### `required`

Field must not be empty. Applies to text inputs, selects, checkboxes, and textareas.

- **Arguments:** none

```html
<input name="username" validate="required" error-required="Username is required" />
```

### `email`

Field must be a valid email address.

- **Arguments:** none

```html
<input name="email" type="email"
       validate="required|email"
       error-email="Please enter a valid email" />
```

### `url`

Field must be a valid URL.

- **Arguments:** none

```html
<input name="website" type="url"
       validate="url"
       error-url="Please enter a valid URL" />
```

### `min`

Minimum numeric value.

- **Arguments:** `value` (number, required) — the minimum allowed value

```html
<input name="age" type="number"
       validate="required|min:18"
       error-min="You must be at least 18" />
```

### `max`

Maximum numeric value.

- **Arguments:** `value` (number, required) — the maximum allowed value

```html
<input name="quantity" type="number"
       validate="required|max:99"
       error-max="Maximum quantity is 99" />
```

### `minlength` (native attribute)

Minimum string length. Uses native ValidityState.

- **Arguments:** `length` (number, required) — the minimum number of characters

```html
<input name="password" type="password"
       validate="required"
       minlength="8"
       error-minlength="Password must be at least 8 characters" />
```

### `maxlength` (native attribute)

Maximum string length. Uses native ValidityState.

- **Arguments:** `length` (number, required) — the maximum number of characters

```html
<textarea name="bio"
          maxlength="500"
          error-maxlength="Bio cannot exceed 500 characters"></textarea>
```

### `pattern` (native attribute)

Regex pattern the value must match. Uses native ValidityState.

- **Arguments:** `regex` (string, required) — a regular expression pattern

```html
<input name="zipcode"
       pattern="[0-9]{5}"
       error-pattern="Enter a 5-digit ZIP code" />
```

### `step` (native attribute)

Numeric step constraint. Uses native ValidityState.

- **Arguments:** `value` (number, required) — the allowed numeric step

```html
<input name="price" type="number"
       step="0.01"
       error-step="Price must be in increments of 0.01" />
```

### `custom`

Runs the validator registered with `NoJS.validator(name, fn)`. The validator receives `(value, formValues)`; rule arguments after the name are not passed. It returns an error string to fail, `true` or a falsy value to pass. To pass arguments, use the validator's name as the rule instead (`validate="match:password"` calls it with `(value, 'password', formValues)`).

- **Arguments:** `name` (string, required) — the registered validator name

```html
<script>
  NoJS.validator('even', (value) => Number(value) % 2 === 0 || 'Value must be an even number');
</script>

<input name="even" type="number" validate="custom:even" />
```

### Empty Values (`validate-empty`)

`validate-empty` (NoJS Elements 1.23+) is opt-in, on the form or on a field (the field wins):

| Value | Behavior |
|-------|----------|
| `check` (default) | `min`, `max` and `url` also check an empty value: `min:1` fails an empty field and `url` fails `""` |
| `skip` | An empty or whitespace-only value passes `min`, `max` and `url`; only `required` reports it |

```html
<form validate="" validate-empty="skip">
  <input name="age" type="number" validate="min:18" />
  <input name="qty" type="number" validate="min:1" validate-empty="check" />
</form>
```

The LSP completes `check` / `skip` in `validate-empty`.

### Registering your own rules

`NoJS.validator(name, fn)` registers a rule that `validate` can use by name. Add the name to [`nojs.customValidators`](configuration.md#nojscustomvalidators) so the LSP completes it and does not report it as unknown.

Only `required`, `email`, `url`, `min` and `max` are reserved: `NoJS.validator()` refuses to override them. Since NoJS 1.22 every other name can be registered, including `minlength`, `maxlength`, `pattern`, `match`, `number`, `integer`, `alpha` and `alphanumeric` (NoJS 1.15–1.21 refused them too). The `validate` directive has no rule with those names, so register them before `@no-js-dev/nojs-elements` loads if you want to use them in `validate`:

```html
<script>
  NoJS.validator('minlength', (value, len) =>
    String(value).length >= Number(len) || `Must be at least ${len} characters`);
</script>

<input name="username" validate="required|minlength:3" />
```

Then add `minlength` to `nojs.customValidators`; otherwise the LSP points you to the native `minlength` attribute.

```html
<!-- Without a registered validator, use the native attribute -->
<input name="username" validate="required" minlength="3" />
```

---

## Companion Attributes

The `validate` directive supports these companion attributes:

| Name | Type | Description |
|------|------|-------------|
| `error` | string | Default error message or template ID (prefix with `#`) |
| `error-*` | string | Per-rule error message or template ID (e.g. `error-required`, `error-email`) |
| `error-class` | string | CSS class(es) applied to invalid fields |
| `validate-on` | string | Validation trigger events (space-separated: `input`, `blur`, `focusout`, `submit`) |
| `validate-if` | expression | Conditional expression; field is only validated when truthy |
| `validate-empty` | string | `check` (default) or `skip`: whether `min`, `max` and `url` check an empty value |
| `as` | identifier | Expose per-field validation state as a context variable |
| `success` | templateId | Success template for form |

---

## `$form` Context

When `validate` is placed on a `<form>` element, No.JS creates a `$form` reactive context accessible by all child elements. Use `$form` properties in expressions to build dynamic form UIs.

| Property | Type | Description |
|----------|------|-------------|
| `$form.valid` | boolean | `true` when all fields pass validation |
| `$form.dirty` | boolean | `true` when any field value has changed |
| `$form.touched` | boolean | `true` when any field has lost focus (or after a submit attempt) |
| `$form.submitting` | boolean | `true` from a valid submit until the form's HTTP request settles or `$form.endSubmit()` runs |
| `$form.pending` | boolean | Reserved for async validators; stays `false` (validators run synchronously) |
| `$form.errors` | object | Error messages keyed by field name (e.g. `$form.errors.email`) |
| `$form.values` | object | Current field values keyed by field name |
| `$form.fields` | object | Per-field state: `valid`, `dirty`, `touched`, `error`, `value` |
| `$form.firstError` | string | The first visible error message |
| `$form.errorCount` | number | Number of fields with a visible error |
| `$form.reset()` | function | Clears dirty / touched / submitting, calls the native `form.reset()` and re-validates (`model` state is not reset) |
| `$form.endSubmit()` | function | Sets `submitting` back to `false`; call it at the end of an `on:submit` handler |

### Usage examples

```html
<!-- Disable submit until valid -->
<button type="submit" bind-disabled="!$form.valid">Submit</button>

<!-- Show error count -->
<span if="$form.errorCount > 0" bind="$form.errorCount + ' error(s)'"></span>

<!-- Display first error -->
<div if="$form.firstError" class="alert" bind="$form.firstError"></div>

<!-- Per-field error display -->
<span if="$form.errors.email" bind="$form.errors.email"></span>

<!-- Reset form -->
<button type="button" on:click="$form.reset()">Reset</button>
```

---

## Custom Validators

Register custom validator names via the `nojs.customValidators` extension setting. This enables LSP completions and suppresses unknown-validator diagnostics for project-specific rules.

```jsonc
// .vscode/settings.json
{
  "nojs.customValidators": ["phone", "postalCode", "strongPassword"]
}
```

Custom validators are then available in `validate` attribute values:

```html
<input name="phone" validate="required|phone" error-phone="Invalid phone number" />
```

---

## Complete Form Example

```html
<form validate="" error-class="is-invalid" validate-on="input blur">
  <div>
    <label>Name</label>
    <input name="name"
           validate="required" minlength="2"
           error-required="Name is required"
           error-minlength="Name must be at least 2 characters" />
    <span if="$form.errors.name" class="error" bind="$form.errors.name"></span>
  </div>

  <div>
    <label>Email</label>
    <input name="email" type="email"
           validate="required|email"
           error-required="Email is required"
           error-email="Enter a valid email address" />
    <span if="$form.errors.email" class="error" bind="$form.errors.email"></span>
  </div>

  <div>
    <label>Password</label>
    <input name="password" type="password"
           validate="required"
           minlength="8"
           error-required="Password is required"
           error-minlength="Password must be at least 8 characters" />
    <span if="$form.errors.password" class="error" bind="$form.errors.password"></span>
  </div>

  <div>
    <label>Age</label>
    <input name="age" type="number"
           validate="required|min:18|max:120"
           error-required="Age is required"
           error-min="You must be at least 18"
           error-max="Maximum age is 120" />
    <span if="$form.errors.age" class="error" bind="$form.errors.age"></span>
  </div>

  <div>
    <label>Website</label>
    <input name="website" type="url"
           validate="url" validate-empty="skip"
           error-url="Enter a valid URL" />
    <span if="$form.errors.website" class="error" bind="$form.errors.website"></span>
  </div>

  <div if="$form.errorCount > 0" class="error-summary">
    <span bind="$form.errorCount + ' error(s) remaining'"></span>
  </div>

  <button type="submit" bind-disabled="!$form.valid">Submit</button>
  <button type="button" on:click="$form.reset()">Reset</button>
</form>
```
