Docs (4.0.0)
class UIFormContext method

addTest

Adds a validation test for the specified field.

addTest<K extends keyof TData>(name: K, f: (test: UIFormContext.ValidationTest<TData[K]>) => void): this

Summary

This method adds a test function to be run each time the form field is changed, or whenever validation is requested explicitly.

The function should accept a single argument, an instance of UIFormContext.ValidationTest, and either return normally or throw an Error. The methods of the provided ValidationTest object can be used to throw relevant errors; otherwise the function may throw any Error instance, such as an AppException object.

Example

// Add a test to verify phone number input
let myFormContext = new UIFormContext({ phone: "" })
  .addTest("phone", (t) => {
    t.required("Phone number is required"); // throws if empty
    t.assert(/^[-+\d ]{8,}$/.test(t.value!),
      "Invalid phone number"); // throws if no regex match
  })

Related