Form Validation

FormValidator class is used to validate user input on forms

Form Validation and Widget Integration Documentation

Home documentation

This document explains how to use the FormValidator class for validating forms and how to integrate it into widgets for user input in a WebApp application.

Overview

In WebApp, the FormValidator class is used to validate user input on forms. This validation is performed on the server side before processing the form data. Once validated, the form data can be used in widgets to display appropriate messages and handle user interactions.

Using FormValidator

The FormValidator class helps in defining validation rules for form fields. Here’s a breakdown of how to set up and use FormValidator.

Example Code: Form Validation in Controller

Below is an example of how to use FormValidator to validate an email form in a Dart controller.

Future<String> exampleEmailSend() async {
    var emailForm = FormValidator(
      name: 'emailForm',
      rq: rq,
      fields: {
        'email': [
          FieldValidator.requiredField(),
          FieldValidator.isEmailField(),
        ],
        'from': [
          FieldValidator.requiredField(),
          FieldValidator.isEmailField(),
        ],
        'subject': [
          FieldValidator.requiredField(),
          FieldValidator.fieldLength(min: 5, max: 255),
        ],
        'message': [
          FieldValidator.requiredField(),
          FieldValidator.fieldLength(min: 5, max: 1000),
        ],
        'host': [
          FieldValidator.requiredField(),
          FieldValidator.fieldLength(min: 5, max: 255),
        ],
        'port': [
          FieldValidator.isNumberField(
            min: 1,
            max: 65535,
            isRequired: true,
          ),
        ],
        'username': [
          FieldValidator.requiredField(),
          FieldValidator.fieldLength(min: 5, max: 255),
        ],
        'password': [
          FieldValidator.requiredField(),
          FieldValidator.fieldLength(min: 5, max: 255),
        ],
        'fromName': [
          FieldValidator.requiredField(),
          FieldValidator.fieldLength(min: 5, max: 255),
        ],
      },
    );

    var resEmailForm = await emailForm.validateAndForm();
    if (resEmailForm.result) {
      var resSendEmail = await MailSender.sendEmail(
        from: rq.get('from'),
        to: [rq.get('email')],
        subject: rq.get('subject'),
        text: rq.get('message'),
        html: rq.get('message'),
        host: rq.get('host'),
        port: rq.get('port', def: 465),
        username: rq.get('username'),
        password: rq.get('password'),
        ssl: rq.get('ssl', def: true),
        allowInsecure: rq.get('allowInsecure', def: true),
        fromName: rq.get('fromName'),
      );

      if (resSendEmail) {
        rq.addParam('sendEmailSuccess', 'Email sent successfully');
      } else {
        rq.addParam('sendEmailFeiled', 'Email not sent');
      }
    }

    rq.addParams({
      'emailForm': resEmailForm.form,
    });

    return renderTemplate('example/email');
}

Explanation

  1. Creating a FormValidator Instance: Define the form and specify validation rules for each field. Use FieldValidator methods to set requirements like required fields, email validation, and field length.
  2. Validating the Form: Call validateAndForm to check if the form data meets the specified rules.
  3. Processing the Form: If validation is successful, proceed with processing (e.g., sending an email). If not, handle validation errors.
  4. Rendering the Template: Add the form results and validation messages to the response and render the appropriate template.

Integrating Form Validation into Widgets

Forms validated with FormValidator can be integrated into HTML templates (widgets) to provide user feedback and interact with the validated data.

Example Widget Integration

Here’s how to use the validated form data in an HTML widget:

<div class="row my-5">
  <h3>Test form validation</h3>
  <div class="card card-primary bg-light my-3">
    <span class="card-body">
      Email: example@uproid.com<br />
      Password: @Test123
    </span>
  </div>
  <? if loginResult != true and user == null ?>
  <div class="card my-3">
    <div class="card-body bg-light">
      <form method="post">
        <div class="mb-3">
          <label for="email" class="form-label">Email address</label>
          <input
            value="<?= loginForm.email.value ?>"
            type="email"
            name="email"
            class="form-control <?= loginForm.email.valid ?>"
            id="email"
            placeholder="Enter your email"
          />
          <div
            class="invalid-feedback <?= 'd-block' if loginForm.email.failed else '' ?>"
          >
            <?= loginForm.email.errorHtml ?>
          </div>
        </div>
        <div class="mb-3">
          <label for="password" class="form-label">Password</label>
          <input
            value="<?= loginForm.password.value ?>"
            type="password"
            name="password"
            class="form-control <?= loginForm.password.valid ?>"
            id="password"
            placeholder="Enter your password"
          />
          <div
            class="invalid-feedback <?= 'd-block' if loginForm.password.failed else '' ?>"
          >
            <?= loginForm.password.errorHtml ?>
          </div>
        </div>
        <button type="submit" class="btn btn-primary btn-lg text-light">
          Login
        </button>
        <div class="mt-3">
          <div class="alert alert-danger">Login error</div>
        </div>
      </form>
    </div>
  </div>
  <? else ?>
  <div class="alert alert-success my-3">
    <div class="row">
      <div class="col">
        Login success! Welcome
        <i><?= user.name ?></i>
      </div>
      <div class="col text-end">
        <a href="/logout" class="btn text-white btn-sm btn-danger">Logout</a>
      </div>
    </div>
  </div>
  <? endif ?>
</div>

Explanation

  1. HTML Structure: The HTML template contains form fields for email and password, including validation feedback. It uses server-side variables to display error messages and form values.
  2. Conditionally Displaying Content: The widget conditionally shows different content based on whether the user is logged in and the result of the form submission.
  3. Integration with Controller: The controller handles form submission, validates data using FormValidator, and passes the results to the template for rendering.

Summary

This documentation outlines how to use FormValidator for form validation in WebApp. By setting up the validation rules in your Dart controller and integrating them into HTML widgets,