| @@ -0,0 +1,947 @@ |
| 1 | +/// Type-safe decoding and validation of HTML form data. A port of the Gleam |
| 2 | +/// package `formal` (hex.pm/packages/formal, Apache-2.0). |
| 3 | +/// |
| 4 | +/// import form |
| 5 | +/// |
| 6 | +/// pub type SignUp { |
| 7 | +/// SignUp(email: String, password: String) |
| 8 | +/// } |
| 9 | +/// |
| 10 | +/// /// A schema that decodes a `SignUp` from form data. |
| 11 | +/// fn signup_schema() -> form.Schema<SignUp> { |
| 12 | +/// use email <- form.field("email", form.parse_email()) |
| 13 | +/// use password <- form.field("password", { |
| 14 | +/// form.parse_string() |
| 15 | +/// |> form.check_string_length_more_than(7) |
| 16 | +/// }) |
| 17 | +/// use _ <- form.field("confirm", { |
| 18 | +/// form.parse_string() |
| 19 | +/// |> form.check_confirms(password) |
| 20 | +/// }) |
| 21 | +/// form.success(SignUp(email: email, password: password)) |
| 22 | +/// } |
| 23 | +/// |
| 24 | +/// A `Schema` describes how to decode a typed value from the key-value |
| 25 | +/// string pairs an HTML form produces. `new` turns it into a `Form`; add |
| 26 | +/// the submitted values (`add_values` takes `http.form_body(req)`'s list |
| 27 | +/// as it is) and `run` gives either the decoded value, or the form with |
| 28 | +/// errors attached, ready to re-render: |
| 29 | +/// |
| 30 | +/// fn handle_submission(values: List<(String, String)>) { |
| 31 | +/// match form.new(signup_schema()) |> form.add_values(values) |> form.run { |
| 32 | +/// Ok(signup) -> // ... use the SignUp value |
| 33 | +/// Error(f) -> // ... re-render, `form.field_error_messages(f, "email")` |
| 34 | +/// } |
| 35 | +/// } |
| 36 | +/// |
| 37 | +/// Parsers (`parse_*`) extract a value from a field's input and are |
| 38 | +/// _short-circuiting_: when one fails, the checks (`check_*`) chained after |
| 39 | +/// it don't run, so `parse_int() |> check_int_more_than(0)` on `"abc"` |
| 40 | +/// reports `[MustBeInt]`, nothing more. Checks don't short-circuit each |
| 41 | +/// other: every failed check adds its error. |
| 42 | + |
| 43 | +import std/float |
| 44 | +import std/list |
| 45 | +import std/result |
| 46 | +import std/string |
| 47 | + |
| 48 | +// ---- types ------------------------------------------------------------------- |
| 49 | + |
| 50 | +/// A form! Created from a `Schema` with the `new` function. |
| 51 | +/// |
| 52 | +/// Supply values to a form with the `add_*` functions and then pass it to the |
| 53 | +/// `run` function to get either the resulting value or any errors. |
| 54 | +/// |
| 55 | +/// Use the `language` function to supply a new translation function to change |
| 56 | +/// the language of the error messages returned by the `field_error_messages` |
| 57 | +/// function. The default language is `en_gb` English. |
| 58 | +pub opaque type Form<model> { |
| 59 | + Form( |
| 60 | + translator: fn(FieldError) -> String |
| 61 | + , values: List<(String, String)> |
| 62 | + , errors: List<(String, List<FieldError>)> |
| 63 | + , run: RunFunction<model> |
| 64 | + ) |
| 65 | +} |
| 66 | + |
| 67 | +type RunFunction<model> = fn( |
| 68 | + List<(String, String)> |
| 69 | +, List<(String, List<FieldError>)> |
| 70 | +) -> (model, List<(String, List<FieldError>)>) |
| 71 | + |
| 72 | +/// A description of how to decode a typed value from form data. This can be |
| 73 | +/// used to create a new form object using the `new` function. |
| 74 | +pub opaque type Schema<model> { Schema(run: RunFunction<model>) } |
| 75 | + |
| 76 | +/// Why a field failed to parse or validate; `en_gb` and `en_us` translate |
| 77 | +/// these into text for the user, or supply your own with `language`. |
| 78 | +@derive(Eq, Show, Debug) |
| 79 | +pub type FieldError { |
| 80 | + MustBePresent |
| 81 | +, MustBeInt |
| 82 | +, MustBeFloat |
| 83 | +, MustBeEmail |
| 84 | +, MustBePhoneNumber |
| 85 | +, MustBeColour |
| 86 | +, MustBeStringLengthMoreThan(limit: Int) |
| 87 | +, MustBeStringLengthLessThan(limit: Int) |
| 88 | +, MustBeIntMoreThan(limit: Int) |
| 89 | +, MustBeIntLessThan(limit: Int) |
| 90 | +, MustBeFloatMoreThan(limit: Float) |
| 91 | +, MustBeFloatLessThan(limit: Float) |
| 92 | +, MustBeAccepted |
| 93 | + /// For confirmation of passwords, etc. Must match the first field. |
| 94 | +, MustConfirm |
| 95 | + /// For values that must be unique, e.g. user email addresses. |
| 96 | +, MustBeUnique |
| 97 | +, CustomError(message: String) |
| 98 | +} |
| 99 | + |
| 100 | +/// A parser extracts a value from form values, converting it to a desired |
| 101 | +/// type and optionally validating the value. Parsers are used with the |
| 102 | +/// `field` function. |
| 103 | +/// |
| 104 | +/// See the `parse_*` and `check_*` functions for more information. |
| 105 | +/// |
| 106 | +/// Functions that start with `parse_*` are _short-circuiting_, so any parser |
| 107 | +/// functions that come afterwards will not be run. For example, given this |
| 108 | +/// code: |
| 109 | +/// |
| 110 | +/// form.parse_int() |> form.check_int_more_than(0) |
| 111 | +/// |
| 112 | +/// If the input is not an int then `parse_int` will fail, causing |
| 113 | +/// `check_int_more_than` not to run, so the errors will be `[MustBeInt]`. |
| 114 | +pub opaque type Parser<value> { |
| 115 | + Parser( |
| 116 | + run: fn(List<String>, CheckingStatus) -> ( |
| 117 | + value |
| 118 | + , CheckingStatus |
| 119 | + , List<FieldError> |
| 120 | + ) |
| 121 | + ) |
| 122 | +} |
| 123 | + |
| 124 | +type CheckingStatus { |
| 125 | + Check |
| 126 | +, DontCheck |
| 127 | +} |
| 128 | + |
| 129 | +// ---- forms ------------------------------------------------------------------- |
| 130 | + |
| 131 | +/// Create a new form from a schema. |
| 132 | +/// |
| 133 | +/// Add values to the form with the `add_*` functions and use `run` to get |
| 134 | +/// either the final value or some errors from the form and values. |
| 135 | +/// |
| 136 | +/// ## Example |
| 137 | +/// |
| 138 | +/// let schema = { |
| 139 | +/// use name <- form.field("name", { |
| 140 | +/// form.parse_string() |> form.check_not_empty |
| 141 | +/// }) |
| 142 | +/// use age <- form.field("age", form.parse_int()) |
| 143 | +/// form.success(Person(name: name, age: age)) |
| 144 | +/// } |
| 145 | +/// let f = form.new(schema) |
| 146 | +pub fn new(schema: Schema<model>) -> Form<model> { |
| 147 | + Form(translator: en_gb, values: [], errors: [], run: schema.run) |
| 148 | +} |
| 149 | + |
| 150 | +/// Supply a translation function that will be used when converting any |
| 151 | +/// `FieldError`s to text that can be presented to the user. |
| 152 | +/// |
| 153 | +/// Built-in languages: |
| 154 | +/// |
| 155 | +/// - `en_gb` |
| 156 | +/// - `en_us` |
| 157 | +/// |
| 158 | +/// These functions are named using the IETF language tag for the language |
| 159 | +/// they translate to. |
| 160 | +/// |
| 161 | +/// If no language is supplied then `en_gb` is used by default. |
| 162 | +pub fn language( |
| 163 | + form: Form<model> |
| 164 | +, translator: fn(FieldError) -> String |
| 165 | +) -> Form<model> { |
| 166 | + Form(..form, translator: translator) |
| 167 | +} |
| 168 | + |
| 169 | +/// Get all the errors within a form. |
| 170 | +/// |
| 171 | +/// If `run` or `add_error` have not been called then there will be no errors. |
| 172 | +pub fn all_errors(form: Form<model>) -> List<(String, List<FieldError>)> { |
| 173 | + form.errors |
| 174 | +} |
| 175 | + |
| 176 | +/// Get all the values within a form. |
| 177 | +pub fn all_values(form: Form<model>) -> List<(String, String)> { |
| 178 | + form.values |
| 179 | +} |
| 180 | + |
| 181 | +/// Get all the values for a given form field. |
| 182 | +/// |
| 183 | +/// ## Examples |
| 184 | +/// |
| 185 | +/// let f = form.new(schema) |
| 186 | +/// |> form.add_int("one", 100) |
| 187 | +/// |> form.add_string("one", "Hello") |
| 188 | +/// |> form.add_string("two", "Hi!") |
| 189 | +/// form.field_values(f, "one") == ["Hello", "100"] |
| 190 | +pub fn field_values(form: Form<model>, name: String) -> List<String> { |
| 191 | + values_of(form.values, name) |
| 192 | +} |
| 193 | + |
| 194 | +/// Get the first value for a given form field. |
| 195 | +/// |
| 196 | +/// ## Examples |
| 197 | +/// |
| 198 | +/// let f = form.new(schema) |> form.add_int("one", 100) |
| 199 | +/// form.field_value(f, "one") == "100" |
| 200 | +/// form.field_value(f, "two") == "" |
| 201 | +pub fn field_value(form: Form<model>, name: String) -> String { |
| 202 | + match values_of(form.values, name) { |
| 203 | + [first, ..] -> first |
| 204 | + , [] -> "" |
| 205 | + } |
| 206 | +} |
| 207 | + |
| 208 | +/// Run a form, returning either the successfully parsed value if there are |
| 209 | +/// no errors, or a new instance of the form with the errors added to the |
| 210 | +/// fields. |
| 211 | +pub fn run(form: Form<model>) -> Result<model, Form<model>> { |
| 212 | + let (value, errors) = form.run(form.values, []) |
| 213 | + match errors { |
| 214 | + [] -> Ok(value) |
| 215 | + , _ -> Error(Form(..form, errors: errors)) |
| 216 | + } |
| 217 | +} |
| 218 | + |
| 219 | +/// Add multiple values to a form. This function is useful for adding values |
| 220 | +/// from a HTTP request form body sent to your server, or from a HTML form |
| 221 | +/// element in your browser-based application. |
| 222 | +/// |
| 223 | +/// ## Example |
| 224 | +/// |
| 225 | +/// form.new(signup_schema()) |
| 226 | +/// |> form.add_values(http.form_body(req)) |
| 227 | +/// |> form.run |
| 228 | +pub fn add_values(form: Form<model>, values: List<(String, String)>) -> Form< |
| 229 | + model |
| 230 | +> { |
| 231 | + Form(..form, values: list.append(values, form.values)) |
| 232 | +} |
| 233 | + |
| 234 | +/// Replace any existing values of a form with new values. This function is |
| 235 | +/// useful for adding values from a HTTP request form body sent to your |
| 236 | +/// server, or from a HTML form element in your browser-based application. |
| 237 | +pub fn set_values(form: Form<model>, values: List<(String, String)>) -> Form< |
| 238 | + model |
| 239 | +> { |
| 240 | + Form(..form, values: values) |
| 241 | +} |
| 242 | + |
| 243 | +/// Add a string value to the form. |
| 244 | +/// |
| 245 | +/// You may want to use this to pre-fill a form with some already-saved |
| 246 | +/// values for the user to edit. |
| 247 | +pub fn add_string(form: Form<model>, field: String, value: String) -> Form< |
| 248 | + model |
| 249 | +> { |
| 250 | + Form(..form, values: [(field, value), ..form.values]) |
| 251 | +} |
| 252 | + |
| 253 | +/// Add an int value to the form. |
| 254 | +/// |
| 255 | +/// You may want to use this to pre-fill a form with some already-saved |
| 256 | +/// values for the user to edit. |
| 257 | +pub fn add_int(form: Form<model>, field: String, value: Int) -> Form<model> { |
| 258 | + Form(..form, values: [(field, show(value)), ..form.values]) |
| 259 | +} |
| 260 | + |
| 261 | +/// Get the error messages for a field, if there are any. |
| 262 | +/// |
| 263 | +/// The text is formatted using the translator function given with the |
| 264 | +/// `language` function. The default translator is `en_gb`. |
| 265 | +pub fn field_error_messages(form: Form<model>, name: String) -> List<String> { |
| 266 | + list.flat_map( |
| 267 | + errors_of(form.errors, name) |
| 268 | + , fn(errors) { list.map(errors, form.translator) } |
| 269 | + ) |
| 270 | +} |
| 271 | + |
| 272 | +/// Get all the form field errors. |
| 273 | +/// |
| 274 | +/// If the `run` function or the `add_error` function have not been called |
| 275 | +/// then the form is clean and won't have any errors yet. |
| 276 | +pub fn field_errors(form: Form<model>, name: String) -> List<FieldError> { |
| 277 | + flatten(errors_of(form.errors, name)) |
| 278 | +} |
| 279 | + |
| 280 | +/// Add an error to one of the fields of the form. |
| 281 | +/// |
| 282 | +/// This function may be useful if you have some additional validation that |
| 283 | +/// runs outside of the form schema and you want to surface the error |
| 284 | +/// messages to the user via the form. |
| 285 | +pub fn add_error(form: Form<model>, name: String, error: FieldError) -> Form< |
| 286 | + model |
| 287 | +> { |
| 288 | + Form(..form, errors: [(name, [error]), ..form.errors]) |
| 289 | +} |
| 290 | + |
| 291 | +// The values of `name` in `pairs`, in order (gleam's `list.key_filter`). |
| 292 | +fn values_of(pairs: List<(String, String)>, name: String) -> List<String> { |
| 293 | + pairs |
| 294 | + |> list.filter( |
| 295 | + fn(pair) { |
| 296 | + match pair { |
| 297 | + (key, _) -> key == name |
| 298 | + } |
| 299 | + } |
| 300 | + ) |
| 301 | + |> list.map( |
| 302 | + fn(pair) { |
| 303 | + match pair { |
| 304 | + (_, value) -> value |
| 305 | + } |
| 306 | + } |
| 307 | + ) |
| 308 | +} |
| 309 | + |
| 310 | +// The error lists of `name` in `pairs`, in order. |
| 311 | +fn errors_of(pairs: List<(String, List<FieldError>)>, name: String) -> List< |
| 312 | + List<FieldError> |
| 313 | +> { |
| 314 | + pairs |
| 315 | + |> list.filter( |
| 316 | + fn(pair) { |
| 317 | + match pair { |
| 318 | + (key, _) -> key == name |
| 319 | + } |
| 320 | + } |
| 321 | + ) |
| 322 | + |> list.map( |
| 323 | + fn(pair) { |
| 324 | + match pair { |
| 325 | + (_, errors) -> errors |
| 326 | + } |
| 327 | + } |
| 328 | + ) |
| 329 | +} |
| 330 | + |
| 331 | +fn flatten(xss: List<List<a>>) -> List<a> { |
| 332 | + list.fold(xss, [], fn(acc, xs) { list.append(acc, xs) }) |
| 333 | +} |
| 334 | + |
| 335 | +// The first occurrence of each error, in order (gleam's `list.unique`). |
| 336 | +fn unique(errors: List<FieldError>) -> List<FieldError> { |
| 337 | + list.reverse( |
| 338 | + list.fold( |
| 339 | + errors |
| 340 | + , [] |
| 341 | + , fn(acc, error) { |
| 342 | + if list.any(acc, fn(seen) { seen == error }) { |
| 343 | + acc |
| 344 | + } else { |
| 345 | + [error, ..acc] |
| 346 | + } |
| 347 | + } |
| 348 | + ) |
| 349 | + ) |
| 350 | +} |
| 351 | + |
| 352 | +// ---- schemas ----------------------------------------------------------------- |
| 353 | + |
| 354 | +/// Add a new parser to the form for a given form field name. |
| 355 | +pub fn field( |
| 356 | + name: String |
| 357 | +, parser: Parser<value> |
| 358 | +, continuation: fn(value) -> Schema<model> |
| 359 | +) -> Schema<model> { |
| 360 | + Schema( |
| 361 | + fn(values, errors) { |
| 362 | + let input = values_of(values, name) |
| 363 | + let (value, _status, new_errors) = parser.run(input, Check) |
| 364 | + let errors = match new_errors { |
| 365 | + [] -> errors |
| 366 | + , _ -> [(name, new_errors), ..errors] |
| 367 | + } |
| 368 | + continuation(value).run(values, errors) |
| 369 | + } |
| 370 | + ) |
| 371 | +} |
| 372 | + |
| 373 | +/// Finalise a schema, having successfully parsed a value. |
| 374 | +pub fn success(value: model) -> Schema<model> { |
| 375 | + Schema(fn(_, errors) { (value, errors) }) |
| 376 | +} |
| 377 | + |
| 378 | +// ---- parsers ----------------------------------------------------------------- |
| 379 | + |
| 380 | +/// A parser that applies another parser to each input value in a list. |
| 381 | +/// |
| 382 | +/// Takes a parser for a single value and returns a parser that can handle |
| 383 | +/// multiple values of the same type. This is useful for form fields that |
| 384 | +/// can have multiple values, such as checkboxes, multi-selects, or just |
| 385 | +/// repeated inputs of other types. |
| 386 | +/// |
| 387 | +/// ## Example |
| 388 | +/// |
| 389 | +/// let schema = { |
| 390 | +/// use tags <- form.field("tag", form.parse_list(form.parse_string())) |
| 391 | +/// form.success(Article(tags: tags)) |
| 392 | +/// } |
| 393 | +/// |
| 394 | +/// This would parse multiple "tag" fields into a list of strings. |
| 395 | +pub fn parse_list(parser: Parser<output>) -> Parser<List<output>> { |
| 396 | + Parser( |
| 397 | + fn(inputs, check) { |
| 398 | + let (values, status, errors) = list.fold( |
| 399 | + inputs |
| 400 | + , ([], Check, []) |
| 401 | + , fn(acc, input) { |
| 402 | + match acc { |
| 403 | + (values, _, errors) -> { |
| 404 | + let (value, status, new_errors) = parser.run([input], check) |
| 405 | + ([value, ..values], status, [new_errors, ..errors]) |
| 406 | + } |
| 407 | + } |
| 408 | + } |
| 409 | + ) |
| 410 | + (list.reverse(values), status, unique(flatten(list.reverse(errors)))) |
| 411 | + } |
| 412 | + ) |
| 413 | +} |
| 414 | + |
| 415 | +/// A parser that applies another parser if there is a non-empty-string |
| 416 | +/// input value for the field. |
| 417 | +/// |
| 418 | +/// ## Example |
| 419 | +/// |
| 420 | +/// let schema = { |
| 421 | +/// use age <- form.field("age", form.parse_optional(form.parse_int())) |
| 422 | +/// form.success(Person(age: age)) |
| 423 | +/// } |
| 424 | +/// |
| 425 | +/// This would parse an int if the form field has text in it, returning |
| 426 | +/// `None` otherwise. |
| 427 | +pub fn parse_optional(parser: Parser<output>) -> Parser<Option<output>> { |
| 428 | + Parser( |
| 429 | + fn(inputs, check) { |
| 430 | + if list.any(inputs, fn(input) { input != "" }) { |
| 431 | + let (value, status, errors) = parser.run(inputs, check) |
| 432 | + (Some(value), status, errors) |
| 433 | + } else { |
| 434 | + (None, check, []) |
| 435 | + } |
| 436 | + } |
| 437 | + ) |
| 438 | +} |
| 439 | + |
| 440 | +/// Parse a bool value from a checkbox type input. |
| 441 | +/// |
| 442 | +/// No value is `False`, while any value (including the empty string) counts |
| 443 | +/// as `True`. A checked checkbox input with no explicitly set value has the |
| 444 | +/// value `"on"`, which is `True`. Unchecked checkbox inputs send no value |
| 445 | +/// when the form is submitted: they are absent from the sent payload. |
| 446 | +/// |
| 447 | +/// ## Example |
| 448 | +/// |
| 449 | +/// let schema = { |
| 450 | +/// use agreed <- form.field("terms-and-conditions", { |
| 451 | +/// form.parse_checkbox() |> form.check_accepted |
| 452 | +/// }) |
| 453 | +/// form.success(Signup(agreed: agreed)) |
| 454 | +/// } |
| 455 | +pub fn parse_checkbox() -> Parser<Bool> { |
| 456 | + Parser( |
| 457 | + fn(inputs, status) { |
| 458 | + match inputs { |
| 459 | + [] -> (False, status, []) |
| 460 | + , _ -> (True, status, []) |
| 461 | + } |
| 462 | + } |
| 463 | + ) |
| 464 | +} |
| 465 | + |
| 466 | +/// Parse a string value. This parser can never fail! |
| 467 | +/// |
| 468 | +/// ## Example |
| 469 | +/// |
| 470 | +/// let schema = { |
| 471 | +/// use name <- form.field("name", { |
| 472 | +/// form.parse_string() |> form.check_not_empty |
| 473 | +/// }) |
| 474 | +/// form.success(Person(name: name)) |
| 475 | +/// } |
| 476 | +pub fn parse_string() -> Parser<String> { |
| 477 | + Parser( |
| 478 | + fn(inputs, status) { |
| 479 | + match inputs { |
| 480 | + [input, ..] -> (input, status, []) |
| 481 | + , [] -> ("", status, []) |
| 482 | + } |
| 483 | + } |
| 484 | + ) |
| 485 | +} |
| 486 | + |
| 487 | +/// A parser for a whole number. |
| 488 | +/// |
| 489 | +/// Returns a `MustBeInt` error if the input cannot be parsed as a valid int. |
| 490 | +/// |
| 491 | +/// ## Example |
| 492 | +/// |
| 493 | +/// let schema = { |
| 494 | +/// use age <- form.field("age", { |
| 495 | +/// form.parse_int() |> form.check_int_more_than(0) |
| 496 | +/// }) |
| 497 | +/// form.success(Person(age: age)) |
| 498 | +/// } |
| 499 | +pub fn parse_int() -> Parser<Int> { |
| 500 | + Parser( |
| 501 | + fn(inputs, status) { |
| 502 | + value_parser(inputs, 0, status, MustBeInt, string.to_int) |
| 503 | + } |
| 504 | + ) |
| 505 | +} |
| 506 | + |
| 507 | +/// A parser for floating point numbers. |
| 508 | +/// |
| 509 | +/// Returns a `MustBeFloat` error if the input cannot be parsed as a float. |
| 510 | +/// |
| 511 | +/// ## Example |
| 512 | +/// |
| 513 | +/// let schema = { |
| 514 | +/// use price <- form.field("price", { |
| 515 | +/// form.parse_float() |> form.check_float_more_than(0.0) |
| 516 | +/// }) |
| 517 | +/// form.success(Product(price: price)) |
| 518 | +/// } |
| 519 | +pub fn parse_float() -> Parser<Float> { |
| 520 | + Parser( |
| 521 | + fn(inputs, status) { |
| 522 | + value_parser( |
| 523 | + inputs |
| 524 | + , 0.0 |
| 525 | + , status |
| 526 | + , MustBeFloat |
| 527 | + , fn(input) { |
| 528 | + match float.parse(input) { |
| 529 | + Ok(number) -> Ok(number) |
| 530 | + , Error(_) -> result.map(string.to_int(input), float.from_int) |
| 531 | + } |
| 532 | + } |
| 533 | + ) |
| 534 | + } |
| 535 | + ) |
| 536 | +} |
| 537 | + |
| 538 | +/// A parser that validates email addresses. |
| 539 | +/// |
| 540 | +/// Performs basic email validation by checking for the presence of an "@" |
| 541 | +/// symbol. Returns a `MustBeEmail` error if the input is not a valid email |
| 542 | +/// format. |
| 543 | +/// |
| 544 | +/// ## Example |
| 545 | +/// |
| 546 | +/// let schema = { |
| 547 | +/// use email <- form.field("email", form.parse_email()) |
| 548 | +/// form.success(Person(email: email)) |
| 549 | +/// } |
| 550 | +pub fn parse_email() -> Parser<String> { |
| 551 | + Parser( |
| 552 | + fn(inputs, status) { |
| 553 | + value_parser( |
| 554 | + inputs |
| 555 | + , "" |
| 556 | + , status |
| 557 | + , MustBeEmail |
| 558 | + , fn(input) { |
| 559 | + if string.contains(input, "@") { Ok(input) } else { Error(()) } |
| 560 | + } |
| 561 | + ) |
| 562 | + } |
| 563 | + ) |
| 564 | +} |
| 565 | + |
| 566 | +/// A parser for phone numbers. |
| 567 | +/// |
| 568 | +/// Phone numbers are checked with these rules: |
| 569 | +/// - Must be between 8 and 15 digits after removing formatting |
| 570 | +/// - Must contain only digits after removing formatting characters |
| 571 | +/// - `+` may optionally be the first character. |
| 572 | +/// - `-`, ` `, `(`, and `)` are permitted, but are removed. |
| 573 | +/// |
| 574 | +/// Returns a `MustBePhoneNumber` error if the input doesn't satisfy these |
| 575 | +/// rules. |
| 576 | +/// |
| 577 | +/// ## Example |
| 578 | +/// |
| 579 | +/// let schema = { |
| 580 | +/// use phone <- form.field("phone", form.parse_phone_number()) |
| 581 | +/// form.success(Person(phone: phone)) |
| 582 | +/// } |
| 583 | +pub fn parse_phone_number() -> Parser<String> { |
| 584 | + Parser( |
| 585 | + fn(inputs, status) { |
| 586 | + value_parser( |
| 587 | + inputs |
| 588 | + , "" |
| 589 | + , status |
| 590 | + , MustBePhoneNumber |
| 591 | + , fn(input) { phone_number_loop(string.chars(input), "", 0) } |
| 592 | + ) |
| 593 | + } |
| 594 | + ) |
| 595 | +} |
| 596 | + |
| 597 | +fn phone_number_loop(input: List<String>, tel: String, size: Int) -> Result< |
| 598 | + String |
| 599 | +, () |
| 600 | +> { |
| 601 | + match input { |
| 602 | + _ if size > 15 -> Error(()) |
| 603 | + , [] -> if size > 7 { Ok(tel) } else { Error(()) } |
| 604 | + , [c, ..rest] -> if c == "+" && tel == "" { |
| 605 | + phone_number_loop(rest, tel, size) |
| 606 | + } else if is_phone_separator(c) && tel != "" { |
| 607 | + phone_number_loop(rest, tel, size) |
| 608 | + } else if is_digit(c) { |
| 609 | + phone_number_loop(rest, tel <> c, size + 1) |
| 610 | + } else { |
| 611 | + Error(()) |
| 612 | + } |
| 613 | + } |
| 614 | +} |
| 615 | + |
| 616 | +fn is_phone_separator(c: String) -> Bool { |
| 617 | + c == "-" || c == "(" || c == ")" || c == " " |
| 618 | +} |
| 619 | + |
| 620 | +fn is_digit(c: String) -> Bool { |
| 621 | + string.contains("0123456789", c) |
| 622 | +} |
| 623 | + |
| 624 | +/// A parser for colour values. |
| 625 | +/// |
| 626 | +/// Parses colour strings in HTML hex format (e.g. "#FF0000", "#00ff00") |
| 627 | +/// and returns the hex colour string. |
| 628 | +/// |
| 629 | +/// Returns a `MustBeColour` error if the input is not a valid hex colour. |
| 630 | +/// |
| 631 | +/// ## Example |
| 632 | +/// |
| 633 | +/// let schema = { |
| 634 | +/// use background <- form.field("background", form.parse_colour()) |
| 635 | +/// form.success(Theme(background: background)) |
| 636 | +/// } |
| 637 | +pub fn parse_colour() -> Parser<String> { |
| 638 | + Parser( |
| 639 | + fn(inputs, status) { |
| 640 | + value_parser( |
| 641 | + inputs |
| 642 | + , "" |
| 643 | + , status |
| 644 | + , MustBeColour |
| 645 | + , fn(input) { |
| 646 | + match string.chars(input) { |
| 647 | + ["#", a, b, c, d, e, f] -> if list.all( |
| 648 | + [a, b, c, d, e, f] |
| 649 | + , is_hex_digit |
| 650 | + ) { |
| 651 | + Ok(input) |
| 652 | + } else { |
| 653 | + Error(()) |
| 654 | + } |
| 655 | + , _ -> Error(()) |
| 656 | + } |
| 657 | + } |
| 658 | + ) |
| 659 | + } |
| 660 | + ) |
| 661 | +} |
| 662 | + |
| 663 | +fn is_hex_digit(c: String) -> Bool { |
| 664 | + string.contains("0123456789abcdefABCDEF", c) |
| 665 | +} |
| 666 | + |
| 667 | +/// Create a custom parser for any type. |
| 668 | +/// |
| 669 | +/// If the parser function fails it must return two values: |
| 670 | +/// - A default "zero" value of the expected type. This will be used to run |
| 671 | +/// the remaining parser code, and then will be discarded. |
| 672 | +/// - An error message string to present to the user. |
| 673 | +/// |
| 674 | +/// ## Examples |
| 675 | +/// |
| 676 | +/// form.parse(fn(input) { |
| 677 | +/// match input { |
| 678 | +/// ["Squirtle", ..] -> Ok(Squirtle) |
| 679 | +/// , ["Bulbasaur", ..] -> Ok(Bulbasaur) |
| 680 | +/// , ["Charmander", ..] -> Ok(Charmander) |
| 681 | +/// , _ -> Error((Squirtle, "must be a starter Pokémon")) |
| 682 | +/// } |
| 683 | +/// }) |
| 684 | +/// |
| 685 | +/// ## Internationalisation |
| 686 | +/// |
| 687 | +/// If your application supports multiple languages you will need to ensure |
| 688 | +/// the error string returned by your parser function is already in the |
| 689 | +/// desired language. |
| 690 | +pub fn parse(parser: fn(List<String>) -> Result<t, (t, String)>) -> Parser<t> { |
| 691 | + Parser( |
| 692 | + fn(input, status) { |
| 693 | + match parser(input) { |
| 694 | + Ok(value) -> (value, status, []) |
| 695 | + , Error(pair) -> match pair { |
| 696 | + (zero, message) -> (zero, DontCheck, [CustomError(message)]) |
| 697 | + } |
| 698 | + } |
| 699 | + } |
| 700 | + ) |
| 701 | +} |
| 702 | + |
| 703 | +/// Convert the parsed value into another, similar to `list.map` or |
| 704 | +/// `result.map`. |
| 705 | +pub fn map(parser: Parser<t1>, mapper: fn(t1) -> t2) -> Parser<t2> { |
| 706 | + Parser( |
| 707 | + fn(input, status) { |
| 708 | + let (value, new_status, errors) = parser.run(input, status) |
| 709 | + (mapper(value), new_status, errors) |
| 710 | + } |
| 711 | + ) |
| 712 | +} |
| 713 | + |
| 714 | +// Run `next` on the first input value; `zero` and `error` when there is no |
| 715 | +// input or `next` fails, skipping any checks chained after the parser. |
| 716 | +fn value_parser( |
| 717 | + inputs: List<String> |
| 718 | +, zero: t |
| 719 | +, status: CheckingStatus |
| 720 | +, error: FieldError |
| 721 | +, next: fn(String) -> Result<t, x> |
| 722 | +) -> (t, CheckingStatus, List<FieldError>) { |
| 723 | + match inputs { |
| 724 | + [input, ..] -> match next(input) { |
| 725 | + Ok(value) -> (value, status, []) |
| 726 | + , Error(_) -> (zero, DontCheck, [error]) |
| 727 | + } |
| 728 | + , _ -> (zero, DontCheck, [error]) |
| 729 | + } |
| 730 | +} |
| 731 | + |
| 732 | +// ---- checks ------------------------------------------------------------------ |
| 733 | + |
| 734 | +/// Add a custom check to the parser. |
| 735 | +/// |
| 736 | +/// ## Examples |
| 737 | +/// |
| 738 | +/// let must_not_be_rude = fn(text) { |
| 739 | +/// if contains_swear_word(text) { |
| 740 | +/// Error("must not be rude") |
| 741 | +/// } else { |
| 742 | +/// Ok(text) |
| 743 | +/// } |
| 744 | +/// } |
| 745 | +/// let schema = { |
| 746 | +/// use name <- form.field("name", { |
| 747 | +/// form.parse_string() |> form.check(must_not_be_rude) |
| 748 | +/// }) |
| 749 | +/// form.success(Profile(name: name)) |
| 750 | +/// } |
| 751 | +/// |
| 752 | +/// ## Internationalisation |
| 753 | +/// |
| 754 | +/// If your application supports multiple languages you will need to ensure |
| 755 | +/// the error string returned by your checker function is already in the |
| 756 | +/// desired language. |
| 757 | +pub fn check(parser: Parser<b>, checker: fn(b) -> Result<b, String>) -> Parser< |
| 758 | + b |
| 759 | +> { |
| 760 | + add_check( |
| 761 | + parser |
| 762 | + , fn(value) { |
| 763 | + match checker(value) { |
| 764 | + Ok(v) -> Ok(v) |
| 765 | + , Error(message) -> Error(CustomError(message)) |
| 766 | + } |
| 767 | + } |
| 768 | + ) |
| 769 | +} |
| 770 | + |
| 771 | +/// Ensure that the string value is not an empty string. |
| 772 | +pub fn check_not_empty(parser: Parser<String>) -> Parser<String> { |
| 773 | + add_check( |
| 774 | + parser |
| 775 | + , fn(x) { |
| 776 | + match x { |
| 777 | + "" -> Error(MustBePresent) |
| 778 | + , _ -> Ok(x) |
| 779 | + } |
| 780 | + } |
| 781 | + ) |
| 782 | +} |
| 783 | + |
| 784 | +/// Ensure that an int is less than a specified limit. |
| 785 | +pub fn check_int_less_than(parser: Parser<Int>, limit: Int) -> Parser<Int> { |
| 786 | + add_check( |
| 787 | + parser |
| 788 | + , fn(x) { if x < limit { Ok(x) } else { Error(MustBeIntLessThan(limit)) } } |
| 789 | + ) |
| 790 | +} |
| 791 | + |
| 792 | +/// Ensure that an int is more than a specified limit. |
| 793 | +pub fn check_int_more_than(parser: Parser<Int>, limit: Int) -> Parser<Int> { |
| 794 | + add_check( |
| 795 | + parser |
| 796 | + , fn(x) { if x > limit { Ok(x) } else { Error(MustBeIntMoreThan(limit)) } } |
| 797 | + ) |
| 798 | +} |
| 799 | + |
| 800 | +/// Ensure that a string is more than a specified length. |
| 801 | +pub fn check_string_length_more_than( |
| 802 | + parser: Parser<String> |
| 803 | +, limit: Int |
| 804 | +) -> Parser<String> { |
| 805 | + add_check( |
| 806 | + parser |
| 807 | + , fn(x) { |
| 808 | + if string.length(x) > limit { |
| 809 | + Ok(x) |
| 810 | + } else { |
| 811 | + Error(MustBeStringLengthMoreThan(limit)) |
| 812 | + } |
| 813 | + } |
| 814 | + ) |
| 815 | +} |
| 816 | + |
| 817 | +/// Ensure that a string is less than a specified length. |
| 818 | +pub fn check_string_length_less_than( |
| 819 | + parser: Parser<String> |
| 820 | +, limit: Int |
| 821 | +) -> Parser<String> { |
| 822 | + add_check( |
| 823 | + parser |
| 824 | + , fn(x) { |
| 825 | + if string.length(x) < limit { |
| 826 | + Ok(x) |
| 827 | + } else { |
| 828 | + Error(MustBeStringLengthLessThan(limit)) |
| 829 | + } |
| 830 | + } |
| 831 | + ) |
| 832 | +} |
| 833 | + |
| 834 | +/// Ensure that a float is more than a specified limit. |
| 835 | +pub fn check_float_more_than(parser: Parser<Float>, limit: Float) -> Parser< |
| 836 | + Float |
| 837 | +> { |
| 838 | + add_check( |
| 839 | + parser |
| 840 | + , fn(x) { if x > limit { Ok(x) } else { Error(MustBeFloatMoreThan(limit)) } } |
| 841 | + ) |
| 842 | +} |
| 843 | + |
| 844 | +/// Ensure that a float is less than a specified limit. |
| 845 | +pub fn check_float_less_than(parser: Parser<Float>, limit: Float) -> Parser< |
| 846 | + Float |
| 847 | +> { |
| 848 | + add_check( |
| 849 | + parser |
| 850 | + , fn(x) { if x < limit { Ok(x) } else { Error(MustBeFloatLessThan(limit)) } } |
| 851 | + ) |
| 852 | +} |
| 853 | + |
| 854 | +/// Ensure that a bool is `True`. |
| 855 | +pub fn check_accepted(parser: Parser<Bool>) -> Parser<Bool> { |
| 856 | + add_check( |
| 857 | + parser |
| 858 | + , fn(x) { |
| 859 | + match x { |
| 860 | + True -> Ok(x) |
| 861 | + , False -> Error(MustBeAccepted) |
| 862 | + } |
| 863 | + } |
| 864 | + ) |
| 865 | +} |
| 866 | + |
| 867 | +/// Ensure that a field equals some other value. Useful for password |
| 868 | +/// confirmation. |
| 869 | +/// |
| 870 | +/// ## Example |
| 871 | +/// |
| 872 | +/// let schema = { |
| 873 | +/// use password <- form.field("password", { |
| 874 | +/// form.parse_string() |> form.check_string_length_more_than(8) |
| 875 | +/// }) |
| 876 | +/// use _ <- form.field("password-confirmation", { |
| 877 | +/// form.parse_string() |> form.check_confirms(password) |
| 878 | +/// }) |
| 879 | +/// form.success(User(password: password)) |
| 880 | +/// } |
| 881 | +pub fn check_confirms(parser: Parser<t>, other: t) -> Parser<t> where Eq<t> { |
| 882 | + add_check( |
| 883 | + parser |
| 884 | + , fn(x) { if x == other { Ok(x) } else { Error(MustConfirm) } } |
| 885 | + ) |
| 886 | +} |
| 887 | + |
| 888 | +fn add_check( |
| 889 | + parser: Parser<b> |
| 890 | +, checker: fn(b) -> Result<b, FieldError> |
| 891 | +) -> Parser<b> { |
| 892 | + Parser( |
| 893 | + fn(inputs, status) { |
| 894 | + let (value, new_status, errors) = parser.run(inputs, status) |
| 895 | + let errors = match new_status { |
| 896 | + Check -> match checker(value) { |
| 897 | + Error(error) -> [error, ..errors] |
| 898 | + , Ok(_) -> errors |
| 899 | + } |
| 900 | + , DontCheck -> errors |
| 901 | + } |
| 902 | + (value, new_status, errors) |
| 903 | + } |
| 904 | + ) |
| 905 | +} |
| 906 | + |
| 907 | +// ---- translations -------------------------------------------------------------- |
| 908 | + |
| 909 | +/// Translates `FieldError`s into strings suitable for showing to the user. |
| 910 | +/// |
| 911 | +/// ## Examples |
| 912 | +/// |
| 913 | +/// form.en_gb(MustBeColour) == "must be a hex colour code" |
| 914 | +pub fn en_gb(error: FieldError) -> String { |
| 915 | + match error { |
| 916 | + MustBeAccepted -> "must be accepted" |
| 917 | + , MustBeColour -> "must be a hex colour code" |
| 918 | + , MustBeEmail -> "must be an email" |
| 919 | + , MustBeFloat -> "must be a number" |
| 920 | + , MustBeFloatLessThan(limit) -> "must be less than {limit}" |
| 921 | + , MustBeFloatMoreThan(limit) -> "must be more than {limit}" |
| 922 | + , MustBeInt -> "must be a whole number" |
| 923 | + , MustBeIntLessThan(limit) -> "must be less than {limit}" |
| 924 | + , MustBeIntMoreThan(limit) -> "must be more than {limit}" |
| 925 | + , MustBePhoneNumber -> "must be a phone number" |
| 926 | + , MustBePresent -> "must not be blank" |
| 927 | + , MustBeStringLengthLessThan(limit) -> "must be less than {limit} characters" |
| 928 | + , MustBeStringLengthMoreThan(limit) -> "must be more than {limit} characters" |
| 929 | + , MustConfirm -> "doesn't match" |
| 930 | + , MustBeUnique -> "is already in use" |
| 931 | + , CustomError(message) -> message |
| 932 | + } |
| 933 | +} |
| 934 | + |
| 935 | +/// Translates `FieldError`s into strings suitable for showing to the user. |
| 936 | +/// |
| 937 | +/// The same as `en_gb`, but with Americanised spelling of the word "color". |
| 938 | +/// |
| 939 | +/// ## Examples |
| 940 | +/// |
| 941 | +/// form.en_us(MustBeColour) == "must be a hex color code" |
| 942 | +pub fn en_us(error: FieldError) -> String { |
| 943 | + match error { |
| 944 | + MustBeColour -> "must be a hex color code" |
| 945 | + , _ -> en_gb(error) |
| 946 | + } |
| 947 | +} |