Validators

Validators are predicates, similar to what you use in privacyInsert/Update Privacy Rules. They are called at the same time, and the error messages (if any) are accumulated to build and throw a compound EntValidationError instance.

Field Validators

Field validators are executed on every insert*() and upsert*() call.

Also, they are fired when an update*() call touches the fields that the validators are attached to. The untouched fields do not trigger re-validation.

export class EntComment extends BaseEnt(cluster, schema) {
  static override configure() {
    return new this.Configuration({
      privacyLoad: [...],
      privacyInsert: [...],
      validators: [
        new FieldIs(
          "message",
          (value, _row, _vc) => value.trim().length > 0,
          "Please provide comment text",
        ),
        new FieldIs(
          "topic_id",
          async (value, _row, vc) => {
            const topic = await EntTopic.loadX(vc, value);
            return Date.now() - topic.created_at.getTime() < 1000 * 3600 * 24;
          },
          "You can only leave comments on topics created today",
        ),
        ...
      ]
    });
  }
}

If you want to build your own custom validation predicate similar to FieldIs, make sure that it implements AbstractIs interface. Otherwise, you won't be able to use it in validators block.

Validators have so much in common with privacy rules that internally, the whole Ent Framework's privacy engine is called Validation.

The use case for validators is enforcing some early integrity checks on Ent fields before saving the Ent to the database. Putting this logic as close to the database layer as possible brings expra firmness to the architecture.

Whole-Row Validators

You can also define RowIs validators that operate with the entire row to be inserted or updated. As opposed to FiledIs, such validators are fired independently on which fields you are modifying.

Using with Zod or Standard Schema

You can also use Zod or any validation library compatibe with Standard Schema:

Basically, when you omit the last message parameter of FieldIs or RowIs constructors, then it's expected that your validator callback returns an object compatible with Zod's safeParse() or Standard Schema's validate() result shape.

Running Validators Manually

Every Ent class exposes a special "constant" VALIDATION static property that allows you to run fields validators manually if needed. Read more about this in Ent API: Configuration and Types.

Last updated

Was this helpful?