Validation: Built in - lordoftheflies/angular-essential-training GitHub Wiki
The Angular forms architecture has support for two approaches to validation, built-in validation and custom validation. You can apply validators to form control objects in your form group and even to the form group objects. Let's start by adding some built-in validators to the form. The built-in validators are available on the validators class found in the Angular forms, scoped package in the media-item-form.component.ts file. We add validators to the import list at the top and down in the new form group method object we can set validators on the form controls. Let's add a pattern validator for the name. We will use a regular expression that only allows strings that are alphanumeric, letters or numbers with support for dashes, spaces and forward slashes. So anything entered for a media item name that does not adhere to that we want to mark as invalid. Now we'll copy that from the sample.txt file in the project. The second parameter option on a new form control is a validator. So we add a call to validators.pattern with a regular expression as its argument to the name control. And we can switch to the browser, give the name field a value with an invalid pattern and if we inspect the name field in the dev tools, we can see that Angular is applying a CSS class named ng-invalid. If we remove the invalid character, we see Angular switch that class to ng-valid. But if we add that character back and click save, we see in the console that the form is still submitting. Angular will track the state of your form but it is up to you to check that before you do your submit logic. Switching back to the code, over in the media-item-form.component.html file, the form model we have set up has a .valid property on it. So down in the submit button, we can add a property binding for the disabled native element property and set that equal to !form.valid. This will disable the submit button when the form does not pass validation. You can also add multiple validation rules to a control. So over in the component class file, we want the name field to be required. The validators class has a composed method that takes an array of validators. So we can cut the current validators.pattern out and then make a call to validators.compose passing it in an array setting the first entry to validators.required, another one of the built-in ones and the second entry to the pattern validator. The form will only report back valid at this point if both validators pass on the field. If we switch over to the browser, we can see the save button in a disabled state because name is empty and if we fill it out with an invalid character, it's still disabled. But if we give it a valid string the save button lights up.