DEV Community

Taisei
Taisei

Posted on

How to Remove a Specific Error with Angular's setErrors()

Introduction

When building forms in Angular, have you ever faced this situation?

"I want to remove only a specific validation error,
but I want to keep the others."

The built-in setErrors() method in Angular makes this harder than expected.

A Common Scenario

Consider a product search form with a price range.
The user inputs minPrice and maxPrice.

The form requires these validations:

  1. Both fields are required (required)
  2. Values must be at least 0 (min)
  3. minPrice <= maxPrice must hold

A Problematic Implementation

Validation rule #3 needs a custom validator.
Many developers try something like this:

// All errors are cleared
if (minPrice <= maxPrice) {
  control.setErrors(null);
}
Enter fullscreen mode Exit fullscreen mode

What's Wrong?

Calling setErrors(null) clears all errors.

For example:

{ required: true, min: true, customError: true }
Enter fullscreen mode Exit fullscreen mode

If you only wanted to remove customError,
required and min are also removed.
As a result, important error messages disappear.

Why Does This Happen?

It's because of how Angular's setErrors works:

setErrors(
  errors: ValidationErrors | null,
  opts: { emitEvent?: boolean } = {}
): void
Enter fullscreen mode Exit fullscreen mode
  • Pass a ValidationErrors object -> replaces current errors
  • Pass null -> means "no errors"

Solution: Remove Only a Specific Error

The safe approach has three steps:

  1. Get the current errors
  2. Delete only the target error
  3. Reset with remaining errors (or null if empty)

Example

const errors = control.errors || {};
delete errors.customError;
control.setErrors(
  Object.keys(errors).length ? errors : null
);
// Result: { required: true, min: true }
Enter fullscreen mode Exit fullscreen mode

Conclusion

Using setErrors(null) blindly may clear needed errors

Key Points:

  • setErrors replaces all existing errors
  • To remove one error, keep others and reset

With this pattern, you can safely handle complex validations.

Top comments (0)