Validation

With Svelte Formly you use core rules or customize your own to validation a form.

List core rules

<script>
  const fields = [{
      ...,
      rules: [
        'required',
        'min:number',
        'max:number',
        'between:number:number',
        'equal:number',
        'email',
        'url'
        'file'
      ]
  }];
</script>

In case you need to use file rule, must to add file attribute to object with rules, ex:

<script>
  const fields = [{
      type: 'file',
      name: 'name-file',
      attributes: {
        id: 'id-field', // optional
        classes: ['form-control'], // optional
        label: 'Image', // optional
      },
      extra: {
        multiple: true, // default = false
      },
      rules: ['file'],
      file: {
        types: 'jpg,gif,png',
        maxsize: 5,
      },
  }];
</script>

Custom rules

<script>
  import { get } from "svelte/store";
  import { Field, valuesForm } from "svelte-formly";

  const fields = [
    {
      type: "text",
      name: "firstname",
      id: "firstname",
      rules: ["required"]
    },
    {
      type: "text",
      name: "lastname",
      id: "lastname",
      rules: ["required", notEqual, customRule2],
      messages: {
        // Custom message error, property name must equal to function name.
        notEqual: "Last name not equal to First name",
        customRule2: 'foo bar'
      }
    }
  ];

  // Custom rule to force field
  function notEqual() {
    const values = get(valuesForm).values;
    if (values.firstname === values.lastname) {
      return false;
    }
    return true;
  }

  function customRule2() {
    // ...others conditions.
  }
</script>