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