Validation: Custom - lordoftheflies/angular-essential-training GitHub Wiki

Okay, let's build a custom validator. To build your own custom validators, you need to create a function that will receive an object, which angular will pass in as either a form control, form group or form array. And that function needs to return no invalid and return an object if invalid. Let's built a year validator for the year field, which is a form control. In the media dash item dash form dot component dot Ts file, we can create a method named year validator and give it a parameter named control that we can set to a type of form control. We want the year field to be optional. So the first bit of logic we will add is to check if the value is empty and if so, return no telling the control that the field is valid. If it makes it past that, we want to convert the value, which is a string into a number. So we can call parseInt on control dot value and capture it to a local variable. And then we will set up a min and max year. Let's assume that 1900 to 2100 is the timeframe that media will have it to run. And then we will set up a min and max year. Let's assume that 1900 to 2100 is the timeframe that media will have its run. And then we will all be onto other things like virtual reality or something. And finally, we check the year value against the min and max and if valid, return no otherwise we'll return an object. The object has a property that represents the validator type in our case year. So we set value to true here, but we could set it to another object with properties and values. This return object is available on the years property of the control for the form field, which we can use in our views for displaying error messages. This object can really be whatever shape you want. We will cover this in the form lesson, on air handling. Okay, the final thing we need to do is add this dot year validator to the form control instantiation for the year. So for the second argument in the new form control call, we set this dot year validator. Note we don't use parentheses here because we want to pass the function reference instead of making a function call. For the built-in validators from angular, we did call those as functions, but that's because those functions actually return a validator function. Here we are handing the form control our year validator function. Ultimately the form control is going to call whatever we hand it as the second argument, when it runs its validation check. If we switch to the browser, we can add a name value to pass that validation. And we can see that the save button is active because we set up the year validator to support the year being empty. Then if we put a year out of range, we see the save button gets disabled, but if we put in a valid year, we get the save button lit up as the form passes the custom validation rule.