Metadata-Version: 2.4
Name: nyxa-forms
Version: 0.0.1
Summary: Form requests + web validation for Nyxa — rule strings, error bags, old input
Author-email: Al-Amin Islam Nerob <alamin@aincoder.com>
License-Expression: MIT
Project-URL: Repository, https://github.com/NyxaDev/Nyxa
Requires-Python: >=3.13
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: nyxa>=0.0.1
Dynamic: license-file

# nyxa-forms

Web validation for the Nyxa framework — injectable `FormRequest`
classes, ~115 pipe-separated string rules, custom rules via `@rule`,
error bags + old input flashing, and redirect-back semantics for HTML
forms.

## Features

- **`FormRequest`** — self-validating request classes injected by type
  into handlers: `rules()`, `authorize(ctx)`, `messages()`,
  `attributes()`, `prepare_for_validation()`, `with_validator()`,
  `after()`, `validated(*keys)`, `errors()`, `input(key)`.
- **`Validator`** — `Validator(data, rules, app=, ctx=)`;
  `await v.validate()`, `v.validated()`, plus `validate_sync` for
  non-async paths. Dot-key paths reach into nested payloads.
- **~115 built-in rules** — presence (`required`, `filled`,
  `present`, `missing`, `prohibited` and their `*_if`/`*_unless`/
  `*_with`/`*_without` variants), exclusion (`exclude*`), comparison
  (`same`, `different`, `gt`/`gte`/`lt`/`lte`, `between`,
  `in`/`not_in`/`in_array`/`any_of`, `multiple_of`), strings
  (`alpha*`, `ascii`, `starts_with`/`ends_with`/`contains`(+`doesnt_*`),
  `regex`/`not_regex`, `lowercase`/`uppercase`, `hex_color`), types
  (`string`, `boolean`, `integer`, `numeric`, `decimal`, `list`,
  `array`, `json`, `file`, `image`, `mimes`/`mimetypes`,
  `extensions`, `dimensions`), numerics (`min`/`max`/`size`,
  `digits*`), dates (`date`, `before`/`after`(+`_or_equal`),
  `date_equals`, `date_format`, `timezone`), network (`url`,
  `active_url`, `ip`/`ipv4`/`ipv6`, `mac_address`), identifiers
  (`uuid`, `ulid`, `email`, `name`, `encoding`), database (`exists`,
  `unique`, `current_password`), and `confirmed`/`nullable`/
  `distinct`/`prohibits`/`enum`.
- **Rule objects** — `Password(min=8, letters=…, mixed_case=…,
  numbers=…, symbols=…)` (alias `PasswordRule`) and `Enum(MyEnum)`
  mix into rule specs alongside strings.
- **`@rule`** — register custom rules:
  `@rule` / `@rule("name")` / `@rule(implicit=True, exclude=True,
  needs_field=True)`; custom rules can shadow built-in names.
- **HTML form semantics** — `FormsExceptionHandler` wraps the app's
  handler: a `ValidationException` on a non-JSON request redirects
  back (303) with errors + old input flashed; JSON requests get 422.
- **`ctx` macros** — `ctx.validate_web(rules)`, `ctx.old(key)`,
  `ctx.errors([key])`, `ctx.back(fallback="/")`.
- **Helpers** — `old(ctx, key)`, `errors(ctx[, key])`,
  `with_errors(ctx, bag)`, `flash_old(ctx, data)`,
  `back(ctx, fallback="/")` from `nyxa_forms.helpers`.
- **`make:request`** — `nyxa make:request StorePostRequest` scaffolds
  a `FormRequest` (`--fields name:type[:rules]`, `--update`,
  `--describe`, `--force`).

## Install

```bash
nyxa add nyxa-forms   # writes config/forms.py
```

## Usage

```python
from nyxa_forms import FormRequest, Password


class StorePost(FormRequest):
    def rules(self):
        return {"title": "required|string|max:255", "password": ["required", Password(min=12, numbers=True)]}

    def authorize(self, ctx):
        return ctx.user is not None


async def store(ctx, request: StorePost):
    data = request.validated()  # only keys that passed rules
```

Inline validation + manual error handling:

```python
async def handler(ctx):
    data = await ctx.validate_web({"email": "required|email"})
```

Custom rule:

```python
from nyxa_forms import rule


@rule
def strong(value, params, data, validator):
    return isinstance(value, str) and len(value) >= 12 or "Too weak."
```

## Public API

- **`FormRequest`** — injectable base (see Usage). Handler params
  typed to a subclass are decoded, authorized, and validated by the
  `FormRequestKind` contract.
- **`Validator`** — `Validator(data, rules, app=None, ctx=None)`;
  `await v.validate() -> dict`, `v.validated() -> dict`,
  `v.errors`, `v.messages`/`v.attributes` overrides.
- **`ValidationException`** — raised on failure (HTTP 422):
  `exc.bag` (`{field: [messages]}`), `exc.data` (submitted payload).
- **`rule`** — decorator registering a rule function
  `(value, params, data, validator) -> bool | str`; keyword flags
  `implicit`, `exclude`, `needs_field`.
- **`Password`** — password-policy rule object:
  `Password(min=8, letters=False, mixed_case=False, numbers=False,
  symbols=False)`; `Password.defaults()`.
- **`PasswordRule`** — alias of `Password`.
- **`Enum`** — enum rule object: `Enum(MyEnum)` accepts member
  instances, backing values, and names.
- **`FormsProvider`** — registers the `FormRequest` contract kind,
  wraps the exception handler, adds the `ctx` macros, contributes
  `make:request`, and writes `config/forms.py` on `nyxa add`.

## Configuration

`nyxa add nyxa-forms` writes `config/forms.py` (`FORMS = {}` —
reserved for validation behavior overrides).

## Testing

```python
v = Validator({"email": "nope"}, {"email": "required|email"})
try:
    await v.validate()
except ValidationException as e:
    assert "email" in e.bag
```

## License

MIT
