passes method
Validates the value using the given context.
Returns true if valid, otherwise false.
Implementation
@override
FutureOr<bool> passes(ValidationContext context) async {
final value = context.value;
final args = context.parameters;
final field = context.attribute;
// specific check: if value is null/empty, unique check usually passes (unless required).
if (value == null || value.toString().trim().isEmpty) {
return true;
}
var tableName = _table;
var columnName = _column;
var ignoreIdValue = _ignoreId;
var ignoreColumnName = _ignoreColumn;
final extraClauses = <Map<String, dynamic>>[];
// Parse string arguments if provided
if (args.isNotEmpty) {
tableName = args[0];
if (args.length > 1 && args[1].toUpperCase() != 'NULL') {
columnName = args[1];
}
if (args.length > 2 && args[2].toUpperCase() != 'NULL') {
ignoreIdValue = args[2];
}
if (args.length > 3 && args[3].toUpperCase() != 'NULL') {
ignoreColumnName = args[3];
}
// Extra where clauses: key,value pairs starting from index 4
for (int i = 4; i < args.length; i += 2) {
if (i + 1 < args.length) {
extraClauses.add({
'column': args[i],
'value': args[i + 1],
});
}
}
}
if (tableName == null) {
throw Exception("UniqueRule requires a table name.");
}
final db = DB.table(tableName);
final dbColumn = columnName ?? field;
// Main unique check
db.where(dbColumn, '=', value);
// Ignore specific ID (for updates)
if (ignoreIdValue != null) {
db.where(ignoreColumnName, '!=', ignoreIdValue);
}
// Apply extra clauses
for (final clause in extraClauses) {
final col = clause['column'];
final val = clause['value'];
if (val == 'NULL') {
db.whereNull(col);
} else if (val == 'NOT_NULL') {
db.whereNotNull(col);
} else {
db.where(col, '=', val);
}
}
// If record exists, then it is NOT unique -> fail.
if (await db.exists()) {
return false;
}
return true;
}