Validations of model objects. ActiveRecord::Base#validates attaches validations to a column of a model, and ActiveRecord::Base#save runs them through validate_model before anything is written: the object is saved only if all of them pass, otherwise its invalid callback receives the column and the id of the validation that failed.

The built-in validations are presence (the value is not nil), min_length and max_length (length of a string in UTF-8 characters), format (the value matches a Lua pattern) and uniqueness (no other row of the table holds the same value, ignoring case unless case_sensitive = true is given along with it; a nil value always passes, which leaves requiring a value to presence). More can be registered with add.

Summary

Methods

Registers a validator, which can then be used with ActiveRecord::Base#validates.
Runs the validations defined on a model, one column at a time.

Methods

ActiveRecord.Validator:add(id, callback)

shared packages/active_record/lib/validator.lua:114

Registers a validator, which can then be used with ActiveRecord::Base#validates. A validator has to call exactly one of the two callbacks it is given.

ActiveRecord.Validator:add('presence', function(model, column, val, opts, success, fail)
  if model[column] != nil then
    success(model)
  else
    fail(model, column, 'presence')
  end
end)

Parameters

  • id String name of the validation, the key used in the options of #validates
  • callback Function receives the model, the column name, the value given for this validation, all validation options of the column, a success callback and an error callback

Returns

  • ActiveRecord::Validator(self)

ActiveRecord.Validator:validate_model(model, success_callback, error_callback)

shared packages/active_record/lib/validator.lua:65

Runs the validations defined on a model, one column at a time. Validators may be asynchronous, so the outcome is reported through the callbacks.

Parameters

  • model ActiveRecord::Base object to validate
  • success_callback Function called with the model once every validation passed
  • error_callback Function called with the model, the column name and an error code as soon as a validation fails

Returns

  • ActiveRecord::Validator/Boolean self, or false if the model has no schema

Defined in