---
title: "Prevent record insert in Apex"
url: "https://blog.beyondthecloud.dev/tips/prevent-record-insert-in-apex"
category: "Apex"
published: "2024-01-02"
---

# Prevent record insert in Apex

You can create validations in the Apex trigger code to prevent the insertion of selected records?

### Prevent record save in Apex

Did you know that:

You can create validations in the Apex trigger code to prevent the insertion of selected records?

```apex
for (SObject record : Trigger.new) {
    if (!isValid(record)) {
        throw new DmlException();
    }
}
```

Prevent saving only records that failed validation:

```apex
for (SObject record : Trigger.new) {
    if (!isValid(record)) {
        record.addError('Validation failed!')
    }
}
```

More details: SObject Class reference
