ryardley / pdsl

The expressive declarative toolkit for composing predicates in TypeScript or JavaScript
https://pdsl.site
MIT License
69 stars 2 forks source link

Schema API changes #127

Closed ryardley closed 4 years ago

ryardley commented 4 years ago

Thinking schema API should be simpler initially

import {schema as p} from "pdsl";

export default MyForm() {
  return <Formik
      initialValues={{
        email: "",
        firstName: "",
        lastName: ""
      }}
      validationSchema={p`{
        email: 
          _         <- "Required" 
          & Email   <- "Invalid email address",
        firstName: 
          _             <- "Required" 
          & string[>2]  <- "Must be longer than 2 characters"
          & string[<20] <- "Nice try nobody has a first name that long",
        lastName: 
          _             <- "Required" 
          & string[>2]  <- "Must be longer than 2 characters"
          & string[<20] <- "Nice try nobody has a last name that long"
      }`}
      onSubmit={values => {
        setTimeout(() => {
          alert(JSON.stringify(values, null, 2));
        }, 500);
      }}
      render={({ errors, touched }) => (
        <Form>
          <label htmlFor="firstName">First Name</label>
          <Field name="firstName" placeholder="Jane" type="text" />

          <ErrorMessage
            name="firstName"
            component="div"
            className="field-error"
          />

          <label htmlFor="lastName">Last Name</label>
          <Field name="lastName" placeholder="Doe" type="text" />
          <ErrorMessage
            name="lastName"
            component="div"
            className="field-error"
          />

          <label htmlFor="email">Email</label>
          <Field name="email" placeholder="jane@acme.com" type="email" />
          <ErrorMessage name="email" component="div" className="field-error" />

          <button type="submit">Submit</button>
          <Debug />
        </Form>
      )}
    />
}

We can offer an escape hatch:

import {configureSchema} from 'pdsl';
const p = configureSchema({throwErrors: false});