# Validation

Validate component properties with Django form fields and validators via a
`rules()` method.

## Defining rules

Validation via a rules() method of Django form fields. Blur the email to validate it live; Submit validates everything.

```interlace-demo
ValidationDemo
```

Define a `rules()` method that returns a dict mapping property names
to Django form fields (or lists of validators). The full Django form-field
library is available.

```python
from django import forms

class ContactForm(Component):
    name: str = ""
    email: str = ""
    message: str = ""

    def rules(self):
        return {
            'name': forms.CharField(min_length=3, max_length=50),
            'email': forms.EmailField(),
            'message': forms.CharField(min_length=10),
        }
```

## Validating

Call `self.validate()` - it returns `True` when all rules
pass and populates `self.errors` otherwise.

```python
    def submit(self):
        if self.validate():
            send_email(self.email, self.message)
            self.name = self.email = self.message = ""  # clear fields
        # On failure, errors are available in the template
```

## Displaying errors

Errors are exposed as `errors.<field>` (a list of messages).

```django
<form>
    <input lace:model="email" />
    {% if errors.email %}
        <span class="text-red-600">{{ errors.email.0 }}</span>
    {% endif %}

    <button lace:click="submit">Submit</button>
</form>
```

## Validating a single field

Instant validation - each field re-validates on every keystroke via validate_only() in the updated() hook.

```interlace-demo
InstantValidation
```

Use `validate_only()` to validate one field at a time - handy for
real-time feedback from an `updated_*` hook.

```python
    def updated_email(self, value):
        self.validate_only('email')
```

## Custom messages

Pass `error_messages` to the form field, keyed by Django's error
codes (`required`, `min_length`, `invalid`, …).

```python
    def rules(self):
        return {
            'name': forms.CharField(
                min_length=3,
                error_messages={
                    'required': 'Please enter your name',
                    'min_length': 'Name must be at least 3 characters',
                },
            ),
        }
```

## Adding errors manually

For validation the rules can't express (e.g. a uniqueness check), call
`add_error()`.

```python
    def submit(self):
        if not self.validate():
            return
        if User.objects.filter(email=self.email).exists():
            self.add_error('email', 'That email is already registered')
            return
        # ... create the user
```
