Validation
You can add validations to models in Accel Record.
Sample Validation
Here is an example of validation for a model.
import { validates } from "accel-record/validations";import { ApplicationRecord } from "./applicationRecord.js";
export class UserModel extends ApplicationRecord { static validations = validates(this, [["firstName", { presence: true }]]);}
import { User } from "./models/index.js";
const user = User.build({ firstName: "" });user.isValid(); // => falseuser.errors.fullMessages(); // => ["FirstName can't be blank"]
user.firstName = "John";user.isValid(); // => true
Validation Execution Timing
When using the save
, update
, and create
methods, validation is automatically executed, and the saving process is only performed if there are no errors.
import { User } from "./models/index.js";
// If a validation error occurs, save or update will return false.const newUser = User.build({ firstName: "" });newUser.save(); // => falsenewUser.errors.fullMessages(); // => ["FirstName can't be blank"]
const user = User.first()!;user.update({ firstName: "" }); // => falsenewUser.errors.fullMessages(); // => ["FirstName can't be blank"]
// If a validation error occurs, create will throw an exception.User.create({ firstName: "" }); // => Error: Failed to create
Validation Definition
You can define validations by using the validates()
function and adding a validations
property to the model class. Alternatively, you can override the validateAttributes()
method of the BaseModel.
model ValidateSample { id Int @id @default(autoincrement()) accepted Boolean pattern String key String count Int size String}
import { Validator } from "accel-record";import { validates } from "accel-record/validations";import { ApplicationRecord } from "./applicationRecord.js";
export class ValidateSampleModel extends ApplicationRecord { static validations = validates(this, [ // Common validations can be easily written using validation helpers. ["accepted", { acceptance: true }], [ "pattern", { length: { minimum: 2, maximum: 5 }, format: { with: /^[a-z]+$/, message: "only allows lowercase letters" }, }, ], ["size", { inclusion: { in: ["small", "medium", "large"] } }], [["key", "size"], { presence: true }],
// Example of using a custom validator MyValidator, ]);
// You can also override the validateAttributes method to define validations. override validateAttributes() { this.validates("key", { uniqueness: true });
// If you want to perform custom validation logic, use the errors.add method to add error messages. if (this.key && !/^[a-z]$/.test(this.key[0])) { this.errors.add("key", "should start with a lowercase letter"); } }}
// Custom validators inherit from Validator and implement the validate method.class MyValidator extends Validator<{ key: string | undefined }> { validate() { if (this.record.key === "xs") { this.errors.add("key", "should not be xs"); } }}