Carlos Cifuentes
AngularJS → Angular reference

form validation (ng-required, $error) in modern Angular

Validation moves from template attributes to the form definition in the component, where it is typed and testable.

Before · AngularJS
<form name="f" ng-submit="f.$valid && vm.save()" novalidate>
  <input name="email" type="email" ng-model="vm.email" required>
  <span ng-show="f.email.$touched && f.email.$error.required">Required</span>
</form>
After · Angular
form = new FormGroup({
  email: new FormControl('', {
    nonNullable: true,
    validators: [Validators.required, Validators.email],
  }),
});

<form [formGroup]="form" (ngSubmit)="save()">
  <input formControlName="email" type="email" />
  @if (form.controls.email.touched && form.controls.email.hasError('required')) {
    <span>Required</span>
  }
</form>

What changes

  • required, minlength and pattern attributes become Validators in the FormControl.
  • $error, $touched and $dirty become hasError(), touched and dirty.
  • Custom validation directives become validator functions.

Migration tip. Forms are where undocumented business rules hide. List every validation of the old form before rebuilding it, and turn each one into a unit test.

Related

Planning a migration or a micro-frontend platform?

In a 20-minute call you describe your situation and I tell you how I'd approach it. If it isn't worth doing yet, I'll say so.

Message me on LinkedIn