App Maker has default validations and regular expression validation which will highlight the fields once the error occurs.
We have requirement to do custom validations to check duplicate records in models. Is there any function to check the validation or do we need to do any script?
The best way to avoid data duplication will be enforcing 'unique' constraint for your tables using Cloud SQL.
In case you don't want to use Cloud SQL and want to go with Drive Tables you can emulate unique constraint manually using locks, queries and model events:
// onCreate model event (actually it is onBeforeCreate)
// this events accepts about-to-create record as parameter
var lock = LockService.getScriptLock();
lock.waitLock(5000);
var query = app.models.MyModel.newQuery();
query.filters.SomeField._equals = record.SomeField;
var records = query.run();
if (records.length > 0) {
throw new Error('Record with SomeField value equal to ' + record.SomeField +
' already exists.');
}
lock.releaseLock();
You need lock
here to prevent other threads concurrently creating records that will violate your unique constraint.
Then you can handle the error on UI in createItem
function callback:
// create button onClick handler
widget.datasource.createItem({
success: function(record) {
// TODO
},
failure: function(error) {
// TODO
}
});