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,
});
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:
- The field path to validate
- A predicate function (your condition)
- 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' });
}
);
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:
- Medium: https://medium.com/@nhannguyenuri/
- Dev: https://dev.to/nhannguyenuri/
- Linkedin: https://www.linkedin.com/in/nhannguyenuri/
- Support Me: https://buymeacoffee.com/nhannguyenuri
Top comments (0)