Read page as text

NIB / DOCUMENTATION

Validation and forms — NibComponents

Build a local validation flow, understand each rule, and keep server errors distinct from drafts.

Open interactive view

Put participating fields inside Form

NibInput and NibTextarea extend FormField<String>. A parent Form can validate, save, and reset them. NibValidator is String? Function(String?): return null when valid and a useful error string when invalid. validate runs the rules; save invokes onSaved callbacks. Neither operation submits data to a backend.

Keep the GlobalKey<FormState> in the screen’s State so it survives rebuilds. Validate before saving. For fields that must be present, place required before format rules so an empty field gets the most useful first message. AutovalidateMode.onUserInteraction is the default for both text widgets.

// Fields and method inside a State class.
final formKey = GlobalKey<FormState>();
String savedEmail = '';
String status = '';

Widget buildForm() => Form(
  key: formKey,
  child: Column(mainAxisSize: MainAxisSize.min, children: [
    NibInput(
      label: 'Email',
      keyboardType: TextInputType.emailAddress,
      validator: NibValidators.compose([
        NibValidators.required('Enter your email.'),
        NibValidators.email(),
      ]),
      onSaved: (value) => savedEmail = value?.trim() ?? '',
    ),
    NibButton(
      label: 'Check details',
      onPressed: () {
        if (formKey.currentState?.validate() != true) return;
        formKey.currentState!.save();
        setState(() => status = 'Details checked for $savedEmail');
      },
    ),
    Text(status),
  ]),
);

Choose and compose the actual rules

compose evaluates validators in order and returns the first error. Except for required, the supplied format and length rules accept a null or empty value. They do not trim or normalize all input uniformly. Decide whether trimming is appropriate for your field; never silently trim passwords.

RuleBehavior and limits
required([message])Rejects null, empty, and whitespace-only values.
minLength(length, [message])Checks String.length for non-empty values.
maxLength(length, [message])Checks String.length for non-empty values.
email([message])Checks the package regex. It does not verify delivery or cover every valid international address.
pattern(RegExp, [message])Uses RegExp.hasMatch. Supply anchors when the whole value must match.
name([message])Trims first; requires a Unicode letter initially, then letters, spaces, apostrophes, or hyphens. This is a restricted policy, not a universal model of names.
phone([message])Trims first; accepts the package 7–20 character pattern with optional leading plus and digits, spaces, hyphens, parentheses, and periods. It does not verify a reachable number.
password(...)Checks length, then requested uppercase, lowercase, number, and special-character requirements in that order.
APITypeDefaultBehavior
NibValidators.composeNibValidator Function(List<NibValidator>)First error winsCombine mandatory and format checks in the order the user should fix them.
NibValidators.passwordNibValidatorminLength: 8; uppercase/lowercase/number: true; special character: falseEnforces the chosen character rules; it is not an account-security or password-strength service.

Keep input limits and validation distinct

A text field’s maxLength controls its input behavior. A validator still matters for values supplied programmatically or loaded from storage. NibValidators.minLength and maxLength use Dart String.length, which counts UTF-16 code units rather than user-perceived grapheme clusters. An emoji or combined character can therefore count differently from Flutter’s visible character counter.

Write a custom NibValidator when the built-in policy does not fit. Keep it synchronous and deterministic. A rule can check a local relationship, such as a confirmation matching a password, but an async server check belongs in the host submission flow. Revalidate dependent fields when the value they depend on changes.

NibValidator projectCode() => (value) {
  if (value == null || value.isEmpty) return null;
  return RegExp(r'^[A-Z]{3}-[0-9]{3}$').hasMatch(value)
      ? null
      : 'Use three capital letters, a dash, and three digits.';
};

Show server feedback without losing the draft

errorText is a host-supplied forced error. The current candidate forwards it to FormField.forceErrorText, so Form.validate fails while it is set and the validator is not evaluated. It takes precedence over the validator and helper text. Keep it in application state, associate it with the submitted value, and clear or replace it when that value changes.

Disable repeated submission while a request is pending, retain the draft on failure, and ignore responses belonging to an older draft. After an await, check mounted before updating the screen. The backend must still validate and authorize the request; a passing local regex is only local feedback.

Loading and asynchronous state ownership

Decide what reset means for the whole form

Form.reset resets participating FormFields. NibInput and NibTextarea write their current FormField.initialValue into the effective controller. Without a controller, that baseline comes from initialValue. With a controller, the widget constructor seeds the baseline from controller.text. A parent rebuild can therefore update that baseline to the current draft. Keep an explicit saved draft in the host if Reset must always restore a particular saved value.

NibCheckbox, NibSwitch, NibSelect, and other selection widgets are not automatically registered as text FormFields by placing them inside Form. Reset their owned values or controllers explicitly. For a required agreement or selection, use a host-owned FormField wrapper or a submission check with visible feedback. Avoid implying that Form.validate has checked values it never received.

Input and textarea controls

Textarea options

Select ownership

Checkbox state

Exercise the failure paths before submitting

Try empty input, whitespace, malformed values, valid values, and programmatic edits. Check which rule reports first and whether fixing a field clears its feedback. Test reset with and without an external controller. Then test a delayed server error arriving after the user has edited the field again.

Use keyboard navigation and increased text scaling while error messages are visible. Keep focus and selection stable during style changes. These checks establish the form’s local interaction contract; they do not validate a production backend that is absent from this example.