Skip to content

A form with validating types ​

One type says what a valid sign-up is. The page uses it to check each field as it's typed, and the server checks the same type again when the call arrives.

lib/server/signup.weft
weft
export type Name = string where it.trim().length >= 2 && it.length <= 60
export type Email = string where it.includes("@") && it.length <= 254
export type Age = number where it.isInteger() && 13 <= it && it < 150
export type Signup = { name: Name, email: Email, age: Age }

let mut people: Signup[] = []

/// Signs someone up; how many have, with them.
export action fn signUp(s: Signup): number {
  people.push(s)
  return people.length
}
routes/page.weft
weft
import { NaN, parseNumber } from "std/math"
import { plural } from "std/format"
import { signUp } from "lib/server/signup"
import type { Signup, Name, Email, Age } from "lib/server/signup"

let mut name = ""
let mut email = ""
let mut age = ""
let mut done = ""

derived nameOk = name is Name
derived emailOk = email is Email
derived ageOk = (try parseNumber(age) else NaN) is Age

async fn submit() {
  let form: json = { name, email, age: try parseNumber(age) else NaN }
  let s, bad = try form as Signup
  if bad != null {
    done = "Check the fields above."
    return
  }
  let count, err = try await signUp(s)
  if err != null {
    done = err.message
    return
  }
  done = `Welcome, ${s.name}. ${plural(count, "person")} signed up so far.`
}
---
<Card className="w-96">
  <CardHeader>
    <CardTitle>Sign up</CardTitle>
  </CardHeader>
  <CardContent className="flex flex-col gap-4">
    <Box class="flex flex-col gap-2">
      <Label>Name</Label>
      <Input bind:value={name} />
      @if name != "" && !nameOk {
        <Text class="text-sm text-destructive">At least two letters.</Text>
      }
    </Box>
    <Box class="flex flex-col gap-2">
      <Label>Email</Label>
      <Input bind:value={email} placeholder="you@example.com" />
      @if email != "" && !emailOk {
        <Text class="text-sm text-destructive">That isn't an email address.</Text>
      }
    </Box>
    <Box class="flex flex-col gap-2">
      <Label>Age</Label>
      <Input bind:value={age} />
      @if age != "" && !ageOk {
        <Text class="text-sm text-destructive">A whole number, 13 or more.</Text>
      }
    </Box>
    <Button disabled={!(nameOk && emailOk && ageOk)} onpress={submit}>Sign up</Button>
    <Text>{done}</Text>
  </CardContent>
</Card>
  • x is Name is true when the condition holds; in a derived value it's recomputed only when name changes.
  • as checks too: form as Signup checks every field of the json value. It can fail, with a CastError { path, expected } naming the first field that doesn't fit (value.age, expected Age), so it takes a try (Errors) and the call never leaves with bad data.
  • The server can't trust the page: signUp's argument is checked again on arrival, and a call with a bad one is refused before signUp runs. The page gets that as the call's NetworkError (a 400), in err.
  • A literal is checked when the program compiles: let me: Email = "not an address" is a compile error.

Conditions are pure Weft, so they can call the module's own pure functions:

lib/slug.weft
weft
fn isSlugChar(c: string): boolean {
  return (c >= "a" && c <= "z") || (c >= "0" && c <= "9") || c == "-"
}

export type Slug = string where it.length > 0 && it.length <= 40 && it.split("").every(isSlugChar)

export fn slugOf(title: string): Slug? {
  let s = title.trim().toLowerCase().replaceAll(" ", "-")
  return if s is Slug { s } else { null }
}

More on validating types: Types.

Weft is in development. The reference is the spec as it stands today.