DEV Community

Nhan Nguyen
Nhan Nguyen

Posted on

Conditional Validation in Angular 21 Signal Forms: `when` vs `applyWhen`

Angular 21's Signal Forms introduce a powerful, declarative approach to conditional validation that makes complex form logic much cleaner. Let's break down the two main approaches: when and applyWhen.

The when Property: Single Rule Conditions

The when property allows you to conditionally apply a single validation rule based on other field values. Perfect for simple conditional requirements:

required(schemaPath.email, {
  message: 'Email is required',
  when: ({ valueOf }) => valueOf(schemaPath.sendViaEmail) === true,
});
Enter fullscreen mode Exit fullscreen mode

Here, the email field is only required when the sendViaEmail checkbox is checked. The valueOf() function gives you reactive access to any field's current value.

The applyWhen Function: Multiple Rule Conditions

When you need to apply multiple validation rules conditionally, reach for applyWhen. It takes three arguments:

  1. The field path to validate
  2. A predicate function (your condition)
  3. A schema function containing all the rules to apply
applyWhen(
  schemaPath.email,
  ({ valueOf }) => valueOf(schemaPath.sendViaEmail) === true,
  (emailPath) => {
    required(emailPath, { message: 'Email is required' });
    email(emailPath, { message: 'Enter a valid email address' });
  }
);
Enter fullscreen mode Exit fullscreen mode

This groups related validation logic together and keeps your schema clean and readable.

When to Use Which?

  • Use when: For single validation rules that need a condition
  • Use applyWhen: For multiple related rules that share the same condition

Both approaches leverage Signal Forms' reactive nature—validation updates automatically as field values change, with no manual subscription management needed.

The Bottom Line

Signal Forms' conditional validation features make complex form logic declarative and maintainable. Whether you're validating a single field or orchestrating multiple dependent rules, the when property and applyWhen function give you the flexibility to express your form's business logic clearly and concisely.

Ready to try Signal Forms? Remember it's currently experimental in Angular 21, but it's already showing promise as the future of Angular forms!

Example

Happy coding!

I hope you found it helpful. Thanks for reading!
Let's get connected! You can find me on:

Top comments (0)