├── .browserslistrc ├── .editorconfig ├── .eslintrc.json ├── .gitignore ├── .vscode ├── extensions.json ├── launch.json └── tasks.json ├── LICENSE ├── README.md ├── angular.json ├── karma.conf.js ├── package-lock.json ├── package.json ├── src ├── app │ ├── address │ │ ├── address-form.component.html │ │ └── address-form.component.ts │ ├── app.component.ts │ ├── app.routes.ts │ ├── company-reactive │ │ ├── address-form-reactive.component.html │ │ ├── address-form-reactive.component.ts │ │ ├── company-form-reactive.component.html │ │ ├── company-form-reactive.component.ts │ │ ├── company-general-form-reactive.component.html │ │ └── company-general-form-reactive.component.ts │ ├── company │ │ ├── company-form.component.html │ │ ├── company-form.component.spec.ts │ │ ├── company-form.component.ts │ │ ├── company-general-form.component.html │ │ ├── company-general-form.component.spec.ts │ │ ├── company-general-form.component.ts │ │ └── company-view.service.ts │ ├── core │ │ ├── form-container-view-provider.ts │ │ ├── imports.ts │ │ ├── index.ts │ │ ├── spinner │ │ │ ├── spinner.component.scss │ │ │ └── spinner.component.ts │ │ └── utils │ │ │ ├── guid.ts │ │ │ ├── index.ts │ │ │ └── utils.ts │ ├── employee │ │ ├── employee-form.component.ts │ │ ├── employee-list.component.ts │ │ └── employee-view.service.ts │ ├── model │ │ ├── address.ts │ │ ├── company.ts │ │ ├── employee-tax.ts │ │ ├── employee.ts │ │ ├── entity-cache.ts │ │ ├── index.ts │ │ └── us-states.ts │ ├── nav-component │ │ ├── nav-component.component.html │ │ ├── nav-component.component.scss │ │ ├── nav-component.component.spec.ts │ │ └── nav-component.component.ts │ ├── services │ │ ├── busy.service.ts │ │ ├── company-form-validation-demo.service.ts │ │ ├── data.service.ts │ │ ├── db.ts │ │ ├── demo-data.ts │ │ ├── fein-validation.service.ts │ │ ├── index.ts │ │ ├── page-leave-guard.ts │ │ ├── remote-data.service.ts │ │ ├── remote-fein-validation.service.ts │ │ └── validation.service.ts │ ├── settings-component │ │ └── settings.component.ts │ ├── teaching-forms │ │ ├── about │ │ │ ├── about-lazy.component.ts │ │ │ └── about.component.ts │ │ ├── address-form-no-widget │ │ │ ├── address-form-no-widget.component.html │ │ │ └── address-form-no-widget.component.ts │ │ ├── address-ngmodule-form │ │ │ ├── address-ngmodule-form.component.html │ │ │ ├── address-ngmodule-form.component.scss │ │ │ ├── address-ngmodule-form.component.spec.ts │ │ │ ├── address-ngmodule-form.component.ts │ │ │ └── address.module.ts │ │ ├── company-general-form-no-widget │ │ │ ├── company-general-form-no-widget.component.html │ │ │ └── company-general-form-no-widget.component.ts │ │ ├── company-general-form-w-widget │ │ │ ├── company-general-form-w-widget.component.html │ │ │ └── company-general-form-w-widget.component.ts │ │ ├── solo-address-form-reactive-w-val │ │ │ ├── solo-address-form.component.html │ │ │ └── solo-address-form.component.ts │ │ └── solo-address-form-reactive │ │ │ ├── solo-address-form.component.html │ │ │ └── solo-address-form.component.ts │ ├── validation │ │ ├── form-field-ng-model.directive.ts │ │ ├── form-validation-scope.directive.ts │ │ ├── index.ts │ │ ├── interfaces.ts │ │ ├── validation-context.ts │ │ ├── validation-fns-reactive.ts │ │ ├── validation-fns.ts │ │ └── validation.d.ts │ ├── validators │ │ ├── address.sync-validations.spec.ts │ │ ├── address.sync-validations.ts │ │ ├── app-validation-context.ts │ │ ├── company.async-validations.spec.ts │ │ ├── company.async-validations.ts │ │ ├── company.sync-validations.spec.ts │ │ ├── company.sync-validations.ts │ │ ├── employee.sync-validations.ts │ │ ├── forbidden-validator.ts │ │ ├── index.ts │ │ ├── unit-test-validation-helpers.ts │ │ ├── unit-test-validation-matcher-types.d.ts │ │ ├── validation-suites.ts │ │ ├── validator.d.ts │ │ └── vest-enforce-extension.ts │ └── widgets │ │ ├── index.ts │ │ ├── input-base.component.ts │ │ ├── input-error.component.ts │ │ ├── input-select.component.ts │ │ ├── input-text.component.ts │ │ └── interfaces.ts ├── assets │ ├── .gitkeep │ └── images │ │ └── green-spinner-on-white.gif ├── environments │ ├── environment.prod.ts │ └── environment.ts ├── favicon.ico ├── global.d.ts ├── index.html ├── main.ts ├── polyfills.ts ├── styles.scss └── test.ts ├── tsconfig.app.json ├── tsconfig.json └── tsconfig.spec.json /.browserslistrc: -------------------------------------------------------------------------------- 1 | # This file is used by the build system to adjust CSS and JS output to support the specified browsers below. 2 | # For additional information regarding the format and rule options, please see: 3 | # https://github.com/browserslist/browserslist#queries 4 | 5 | # For the full list of supported browsers by the Angular framework, please see: 6 | # https://angular.io/guide/browser-support 7 | 8 | # You can see what browsers were selected by your queries by running: 9 | # npx browserslist 10 | 11 | last 1 Chrome version 12 | last 1 Firefox version 13 | last 2 Edge major versions 14 | last 2 Safari major versions 15 | last 2 iOS major versions 16 | Firefox ESR 17 | -------------------------------------------------------------------------------- /.editorconfig: -------------------------------------------------------------------------------- 1 | # Editor configuration, see https://editorconfig.org 2 | root = true 3 | 4 | [*] 5 | charset = utf-8 6 | indent_style = space 7 | indent_size = 2 8 | insert_final_newline = true 9 | trim_trailing_whitespace = true 10 | 11 | [*.ts] 12 | quote_type = single 13 | 14 | [*.md] 15 | max_line_length = off 16 | trim_trailing_whitespace = false 17 | -------------------------------------------------------------------------------- /.eslintrc.json: -------------------------------------------------------------------------------- 1 | { 2 | "root": true, 3 | "ignorePatterns": [ 4 | "projects/**/*" 5 | ], 6 | "overrides": [ 7 | { 8 | "files": [ 9 | "*.ts" 10 | ], 11 | "parserOptions": { 12 | "project": [ 13 | "tsconfig.json" 14 | ], 15 | "createDefaultProgram": true 16 | }, 17 | "extends": [ 18 | "plugin:@angular-eslint/recommended", 19 | "plugin:@angular-eslint/template/process-inline-templates" 20 | ], 21 | "rules": { 22 | "@angular-eslint/directive-selector": [ 23 | "error", 24 | { 25 | "type": "attribute", 26 | "prefix": "app", 27 | "style": "camelCase" 28 | } 29 | ], 30 | "@angular-eslint/component-selector": [ 31 | "error", 32 | { 33 | "type": "element", 34 | "prefix": "app", 35 | "style": "kebab-case" 36 | } 37 | ] 38 | } 39 | }, 40 | { 41 | "files": [ 42 | "*.html" 43 | ], 44 | "extends": [ 45 | "plugin:@angular-eslint/template/recommended" 46 | ], 47 | "rules": {} 48 | } 49 | ] 50 | } 51 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # See http://help.github.com/ignore-files/ for more about ignoring files. 2 | 3 | # Compiled output 4 | /dist 5 | /tmp 6 | /out-tsc 7 | /bazel-out 8 | 9 | # Node 10 | /node_modules 11 | npm-debug.log 12 | yarn-error.log 13 | 14 | # IDEs and editors 15 | .idea/ 16 | .project 17 | .classpath 18 | .c9/ 19 | *.launch 20 | .settings/ 21 | *.sublime-workspace 22 | 23 | # Visual Studio Code 24 | .vscode/* 25 | !.vscode/settings.json 26 | !.vscode/tasks.json 27 | !.vscode/launch.json 28 | !.vscode/extensions.json 29 | .history/* 30 | 31 | # Miscellaneous 32 | /.angular/cache 33 | .sass-cache/ 34 | /connect.lock 35 | /coverage 36 | /libpeerconnection.log 37 | testem.log 38 | /typings 39 | 40 | # System files 41 | .DS_Store 42 | Thumbs.db 43 | -------------------------------------------------------------------------------- /.vscode/extensions.json: -------------------------------------------------------------------------------- 1 | { 2 | // For more information, visit: https://go.microsoft.com/fwlink/?linkid=827846 3 | "recommendations": ["angular.ng-template"] 4 | } 5 | -------------------------------------------------------------------------------- /.vscode/launch.json: -------------------------------------------------------------------------------- 1 | { 2 | // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 3 | "version": "0.2.0", 4 | "configurations": [ 5 | { 6 | "name": "ng serve", 7 | "type": "pwa-chrome", 8 | "request": "launch", 9 | "preLaunchTask": "npm: start", 10 | "url": "http://localhost:4200/" 11 | }, 12 | { 13 | "name": "ng test", 14 | "type": "chrome", 15 | "request": "launch", 16 | "preLaunchTask": "npm: test", 17 | "url": "http://localhost:9876/debug.html" 18 | } 19 | ] 20 | } 21 | -------------------------------------------------------------------------------- /.vscode/tasks.json: -------------------------------------------------------------------------------- 1 | { 2 | // For more information, visit: https://go.microsoft.com/fwlink/?LinkId=733558 3 | "version": "2.0.0", 4 | "tasks": [ 5 | { 6 | "type": "npm", 7 | "script": "start", 8 | "isBackground": true, 9 | "problemMatcher": { 10 | "owner": "typescript", 11 | "pattern": "$tsc", 12 | "background": { 13 | "activeOnStart": true, 14 | "beginsPattern": { 15 | "regexp": "(.*?)" 16 | }, 17 | "endsPattern": { 18 | "regexp": "bundle generation complete" 19 | } 20 | } 21 | } 22 | }, 23 | { 24 | "type": "npm", 25 | "script": "test", 26 | "isBackground": true, 27 | "problemMatcher": { 28 | "owner": "typescript", 29 | "pattern": "$tsc", 30 | "background": { 31 | "activeOnStart": true, 32 | "beginsPattern": { 33 | "regexp": "(.*?)" 34 | }, 35 | "endsPattern": { 36 | "regexp": "bundle generation complete" 37 | } 38 | } 39 | } 40 | } 41 | ] 42 | } 43 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2022 Ward Bell 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Ngc Validate 2 | 3 | Demonstrates Model-Driven validation, in contrast to the Form-Driven validation that we are taught in the Angular docs. 4 | 5 | The initial audience is a talk I'm giving at NgConf 2022 on Model-Driven Validation. 6 | 7 | This project contains 8 | 9 | 1. A sample app, a mini-version of a Payroll Service Enrollment Application, to demonstrate model-driven validation with [Angular Forms](https://angular.io/guide/forms-overview) and the [vest.js validation library](https://vestjs.dev/). 10 | 11 | 1. The "glue" code to integrate Angular Forms with vest.js (see the `validation` folder.) 12 | 13 | 1. Suites of vest.js validation rules for the sample app (see the `validators` folder). 14 | 15 | > Coincidentally, the sample app also demonstrates "Standalone Components" and other new features of Angular v14. 16 | 17 | ### License 18 | 19 | MIT. Please steal anything you see that you like! 20 | 21 | ### Form-Driven Validation 22 | 23 | In Form-Driven validation, each form component validates user input to _its own controls_ using validation rules embedded in the component's logic. These rules only are only applied when the user is entering data on that form. 24 | 25 | With [Angular Form validation](https://angular.io/guide/form-validation), you add validator functions ... one by one ... to each form control. 26 | 27 | There are stock validators (`required`, `min`, `max`, ...) for common cases but you'll probably write custom validator functions for specific business rules and to cover the conditional application of a rule (ex: "_is required but only if some other field has value x_"). 28 | 29 | Developing, maintaining, and consistently applying these property-level rules quickly becomes overwhelming with even simple real world applications. 30 | 31 | Other limitations are more severe: 32 | 33 | * There is no mechanism for applying these rules outside of the form. 34 | 35 | * There is no way to detect if a user's change - perhaps a change that is valid on the current form - invalidates some other part of the domain model that isn't displayed on that form. 36 | 37 | * While _individual_ validators are easy to test, testing that the form _applies all of the rules appropriately_ is hard. 38 | 39 | ### Model-Driven Validation 40 | 41 | In Model-Driven validation, you extract validation rules into a separate "library" of rules that are aligned with the entities in the application's domain model. 42 | 43 | For example, the sample app has collections ("suites") of rules for the Company, Address, Employee, and EmployeeTax model types. 44 | 45 | We still need to validate user form input. We do that by _wiring_ the "validation suites" into Angular Form validation. 46 | 47 | The critical difference from Form Validation is that we can also validate models _outside_ of a form. That allows us to 48 | 49 | * detect validation errors that propagate anywhere in the domain. 50 | * unit test validation suites with mock model data. 51 | * use the same validation rules on client and server. 52 | 53 | ## Vest validation Library 54 | 55 | We write model validation rules in this project with the open-source [vest.js validation library](https://vestjs.dev/). 56 | 57 | Vest validation emulates the style of unit tests. Each vest validation rule is a "test". You collect these "tests" into "suites". You execute those suites to run validation. 58 | 59 | Validation tests can be synchronous or asynchronous. 60 | 61 | The vest validation suites in this sample app are all in the `validators` folder. For example, see `validators/address.sync-validations.ts`. 62 | 63 | Vest is elegant, well-documented, easy to learn, and easy to use. 64 | Check it out! 65 | 66 | ## Angular / Vest Integration 67 | 68 | This project provides the "glue" code to integrate Angular Forms validation with vest validation suites. 69 | 70 | All of the glue is in a few small files in the `validation` folder. 71 | You can copy and re-purpose these files into your own application, following the example set here. Feel free to improve the glue! 72 | 73 | A full description of the integration is TBD. Here is a brief summary. 74 | 75 | Two special Angular validator functions in `validation/validation-fns.ts` - one synchronous and one asynchronous - send the form control changes to model-specific vest validation suites. 76 | 77 | These are the _only validator functions_ a form control ever needs! 78 | 79 | **Reactive Forms** developers can use `addValidatorsToControls` to add these validators to form controls as in this example: 80 | 81 | ``` 82 | protected generalForm = this.fb.group({ 83 | legalName: '', 84 | }); 85 | 86 | constructor(private fb: FormBuilder, private parent: NgForm) { 87 | addValidatorsToControls(this.generalForm.controls, companySyncValidationSuite); 88 | } 89 | ``` 90 | 91 | **Template-Driven Forms** developers have even less to do, after a little setup. 92 | 93 | First, you create mappings of "model type" to vest suites. Here is an example for the _Address_ and _Company_ synchronous validation suites: 94 | 95 | ``` 96 | export const syncValidationSuites: Indexable = { 97 | address: addressSyncValidationSuite, 98 | company: companySyncValidationSuite, 99 | }; 100 | ``` 101 | 102 | Then you register these mappings with Angular dependency injection, perhaps in `main.ts`. 103 | ``` 104 | { provide: SYNC_VALIDATION_SUITES, useValue: syncValidationSuites }, 105 | ``` 106 | 107 | **_Setup is done!_** 108 | 109 | Now your validation suites will be discoverable by the `FormFieldNgModelDirective` that wires your validation suites to HTML elements with `ngModel` attributes. 110 | 111 | The `FormFieldNgModelDirective` automatically adds configured validators to the `NgModelControl` that Angular silently creates for an element with an `ngModel` attribute. 112 | 113 | Here's an example: 114 | ``` 115 | 116 | ``` 117 | 118 | The `name` is the model property to validate. The `[model]` is the data model. The `modelType` identifies the validation suite, via the mapping you setup earlier. 119 | 120 | It would be tedious to repeat the `model` and `modelType` for every form field. Fortunately you don't have to. 121 | 122 | You can set the "validation scope" at a higher level of the form control tree, thanks to the `FormValidationModelDirective`. 123 | 124 | If you don't specify the `model` and `modelType` at the element level, the `FormFieldNgModelDirective` will look up the control tree for the nearest validation scope. 125 | 126 | In this next example, we set the validation scope at the `
` element. 127 | 128 | ``` 129 | 130 | ``` 131 | 132 | Now we can re-write the early `` example, omitting the `model` and `modelType`, knowing that these values will be found at the `` level: 133 | ``` 134 | 135 | ``` 136 | 137 | Notice that there is no special markup on that `` element. It looks like a normal Angular `ngModel` binding ... and it _just works_! 138 | 139 | ## Simplify with Input Wrappers 140 | 141 | A typical application presents and asks for user input in a consistent way. For example, you might show 142 | * a label, 143 | * an input element, 144 | * an error message when the field fails validation. 145 | 146 | The HTML for that pattern could look like this: 147 | 148 | ``` 149 | 150 | 151 | 152 | {{ input.errors['error'] }} 153 | 154 | 155 | ``` 156 | 157 | Such repetitive HTML makes for an ugly, bloated template after only a few fields. 158 | 159 | We strongly suggest that you wrap such patterns in custom input components, tailored to your application. You can also hide that ugly `ngModel` attribute while your at it. 160 | 161 | Here is what that same HTML _could_ look like, using the `InputTextComponent` in the `widgets` folder: 162 | 163 | ``` 164 | 165 | ``` 166 | 167 | Of course you'll want to adapt that component to your application needs. 168 | 169 | # Building and Running 170 | 171 | This project was generated with [Angular CLI](https://github.com/angular/angular-cli) version 14.0.0. 172 | 173 | ## Development server 174 | 175 | Run `ng serve` for a dev server. Navigate to `http://localhost:4200/`. The application will automatically reload if you change any of the source files. 176 | 177 | ## Code scaffolding 178 | 179 | Run `ng generate component component-name` to generate a new component. You can also use `ng generate directive|pipe|service|class|guard|interface|enum|module`. 180 | 181 | ## Build 182 | 183 | Run `ng build` to build the project. The build artifacts will be stored in the `dist/` directory. 184 | 185 | ## Running unit tests 186 | 187 | Run `ng test` to execute the unit tests via [Karma](https://karma-runner.github.io). 188 | 189 | ## Running end-to-end tests 190 | 191 | Run `ng e2e` to execute the end-to-end tests via a platform of your choice. To use this command, you need to first add a package that implements end-to-end testing capabilities. 192 | 193 | ## Further help 194 | 195 | To get more help on the Angular CLI use `ng help` or go check out the [Angular CLI Overview and Command Reference](https://angular.io/cli) page. 196 | -------------------------------------------------------------------------------- /angular.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "./node_modules/@angular/cli/lib/config/schema.json", 3 | "version": 1, 4 | "newProjectRoot": "projects", 5 | "projects": { 6 | "ngc-validate": { 7 | "projectType": "application", 8 | "schematics": { 9 | "@schematics/angular:component": { 10 | "style": "scss" 11 | }, 12 | "@schematics/angular:application": { 13 | "strict": true 14 | } 15 | }, 16 | "root": "", 17 | "sourceRoot": "src", 18 | "prefix": "app", 19 | "architect": { 20 | "build": { 21 | "builder": "@angular-devkit/build-angular:browser", 22 | "options": { 23 | "outputPath": "dist/ngc-validate", 24 | "index": "src/index.html", 25 | "main": "src/main.ts", 26 | "polyfills": "src/polyfills.ts", 27 | "tsConfig": "tsconfig.app.json", 28 | "inlineStyleLanguage": "scss", 29 | "assets": [ 30 | "src/favicon.ico", 31 | "src/assets" 32 | ], 33 | "styles": [ 34 | "./node_modules/@angular/material/prebuilt-themes/indigo-pink.css", 35 | "src/styles.scss" 36 | ], 37 | "scripts": [] 38 | }, 39 | "configurations": { 40 | "production": { 41 | "budgets": [ 42 | { 43 | "type": "initial", 44 | "maximumWarning": "500kb", 45 | "maximumError": "1mb" 46 | }, 47 | { 48 | "type": "anyComponentStyle", 49 | "maximumWarning": "2kb", 50 | "maximumError": "4kb" 51 | } 52 | ], 53 | "fileReplacements": [ 54 | { 55 | "replace": "src/environments/environment.ts", 56 | "with": "src/environments/environment.prod.ts" 57 | } 58 | ], 59 | "outputHashing": "all" 60 | }, 61 | "development": { 62 | "buildOptimizer": false, 63 | "optimization": false, 64 | "vendorChunk": true, 65 | "extractLicenses": false, 66 | "sourceMap": true, 67 | "namedChunks": true 68 | } 69 | }, 70 | "defaultConfiguration": "production" 71 | }, 72 | "serve": { 73 | "builder": "@angular-devkit/build-angular:dev-server", 74 | "configurations": { 75 | "production": { 76 | "browserTarget": "ngc-validate:build:production" 77 | }, 78 | "development": { 79 | "browserTarget": "ngc-validate:build:development" 80 | } 81 | }, 82 | "defaultConfiguration": "development" 83 | }, 84 | "extract-i18n": { 85 | "builder": "@angular-devkit/build-angular:extract-i18n", 86 | "options": { 87 | "browserTarget": "ngc-validate:build" 88 | } 89 | }, 90 | "test": { 91 | "builder": "@angular-devkit/build-angular:karma", 92 | "options": { 93 | "main": "src/test.ts", 94 | "polyfills": "src/polyfills.ts", 95 | "tsConfig": "tsconfig.spec.json", 96 | "karmaConfig": "karma.conf.js", 97 | "inlineStyleLanguage": "scss", 98 | "assets": [ 99 | "src/favicon.ico", 100 | "src/assets" 101 | ], 102 | "styles": [ 103 | "./node_modules/@angular/material/prebuilt-themes/indigo-pink.css", 104 | "src/styles.scss" 105 | ], 106 | "scripts": [] 107 | } 108 | }, 109 | "lint": { 110 | "builder": "@angular-eslint/builder:lint", 111 | "options": { 112 | "lintFilePatterns": [ 113 | "src/**/*.ts", 114 | "src/**/*.html" 115 | ] 116 | } 117 | } 118 | } 119 | } 120 | }, 121 | "cli": { 122 | "analytics": "0e8a1365-6b77-48b2-aa5c-a73b06a69a08", 123 | "schematicCollections": [ 124 | "@angular-eslint/schematics" 125 | ] 126 | } 127 | } 128 | -------------------------------------------------------------------------------- /karma.conf.js: -------------------------------------------------------------------------------- 1 | // Karma configuration file, see link for more information 2 | // https://karma-runner.github.io/1.0/config/configuration-file.html 3 | 4 | module.exports = function (config) { 5 | config.set({ 6 | basePath: '', 7 | frameworks: ['jasmine', '@angular-devkit/build-angular'], 8 | plugins: [ 9 | require('karma-jasmine'), 10 | require('karma-chrome-launcher'), 11 | require('karma-jasmine-html-reporter'), 12 | require('karma-coverage'), 13 | require('@angular-devkit/build-angular/plugins/karma') 14 | ], 15 | client: { 16 | jasmine: { 17 | // you can add configuration options for Jasmine here 18 | // the possible options are listed at https://jasmine.github.io/api/edge/Configuration.html 19 | // for example, you can disable the random execution with `random: false` 20 | // or set a specific seed with `seed: 4321` 21 | }, 22 | clearContext: false // leave Jasmine Spec Runner output visible in browser 23 | }, 24 | jasmineHtmlReporter: { 25 | suppressAll: true // removes the duplicated traces 26 | }, 27 | coverageReporter: { 28 | dir: require('path').join(__dirname, './coverage/ngc-validate'), 29 | subdir: '.', 30 | reporters: [ 31 | { type: 'html' }, 32 | { type: 'text-summary' } 33 | ] 34 | }, 35 | reporters: ['progress', 'kjhtml'], 36 | port: 9876, 37 | colors: true, 38 | logLevel: config.LOG_INFO, 39 | autoWatch: true, 40 | browsers: ['Chrome'], 41 | singleRun: false, 42 | restartOnFileChange: true 43 | }); 44 | }; 45 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "ngc-validate", 3 | "version": "0.0.0", 4 | "scripts": { 5 | "ng": "ng", 6 | "start": "ng serve", 7 | "build": "ng build", 8 | "watch": "ng build --watch --configuration development", 9 | "test": "ng test", 10 | "lint": "ng lint" 11 | }, 12 | "private": true, 13 | "dependencies": { 14 | "@angular/animations": "^14.2.0", 15 | "@angular/cdk": "^14.2.0", 16 | "@angular/common": "^14.2.0", 17 | "@angular/compiler": "^14.2.0", 18 | "@angular/core": "^14.2.0", 19 | "@angular/forms": "^14.2.0", 20 | "@angular/material": "^14.2.0", 21 | "@angular/platform-browser": "^14.2.0", 22 | "@angular/platform-browser-dynamic": "^14.2.0", 23 | "@angular/router": "^14.2.0", 24 | "rxjs": "~7.5.6", 25 | "tslib": "^2.4.0", 26 | "validator": "^13.7.0", 27 | "vest": "^4.6.5", 28 | "zone.js": "~0.11.8" 29 | }, 30 | "devDependencies": { 31 | "@angular-devkit/build-angular": "^14.2.1", 32 | "@angular-eslint/builder": "14.0.3", 33 | "@angular-eslint/eslint-plugin": "14.0.3", 34 | "@angular-eslint/eslint-plugin-template": "14.0.3", 35 | "@angular-eslint/schematics": "14.0.3", 36 | "@angular-eslint/template-parser": "14.0.3", 37 | "@angular/cli": "~14.2.1", 38 | "@angular/compiler-cli": "^14.2.0", 39 | "@types/jasmine": "~4.3.0", 40 | "@typescript-eslint/eslint-plugin": "5.35.1", 41 | "@typescript-eslint/parser": "5.35.0", 42 | "eslint": "^8.23.0", 43 | "jasmine-core": "~4.1.0", 44 | "karma": "~6.3.0", 45 | "karma-chrome-launcher": "~3.1.0", 46 | "karma-coverage": "~2.2.0", 47 | "karma-jasmine": "~5.0.0", 48 | "karma-jasmine-html-reporter": "~1.7.0", 49 | "typescript": "~4.8.2" 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /src/app/address/address-form.component.html: -------------------------------------------------------------------------------- 1 |
2 |
3 | 4 | 5 |
6 |
7 | 8 | 9 |
10 |
11 | 12 |
13 |
14 | -------------------------------------------------------------------------------- /src/app/address/address-form.component.ts: -------------------------------------------------------------------------------- 1 | import { Component, Input } from '@angular/core'; 2 | 3 | import { Address } from '@model'; 4 | import { formContainerViewProvider } from '@core'; 5 | import { FORMS } from '@imports'; 6 | import { toSelectOptions } from '@app/widgets'; 7 | import { UsStates } from '@model'; 8 | 9 | const states = toSelectOptions(UsStates, 'name', 'abbreviation'); 10 | 11 | @Component({ 12 | selector: 'app-address-form', 13 | standalone: true, 14 | templateUrl: './address-form.component.html', 15 | viewProviders: [formContainerViewProvider], 16 | imports: [FORMS], 17 | }) 18 | export class AddressFormComponent { 19 | @Input() vm?: Address 20 | 21 | /** Name for the formGroup when added to the parent form. Defaults to 'address'. */ 22 | // eslint-disable-next-line @angular-eslint/no-input-rename 23 | @Input('name') ngModelGroupName = 'address'; 24 | 25 | states = states; 26 | } 27 | -------------------------------------------------------------------------------- /src/app/app.component.ts: -------------------------------------------------------------------------------- 1 | import { Component } from '@angular/core'; 2 | import { ROUTER } from '@imports'; 3 | import { NavComponentComponent } from './nav-component/nav-component.component'; 4 | import { SpinnerComponent } from '@core/spinner/spinner.component'; 5 | 6 | @Component({ 7 | selector: 'app-root', 8 | standalone: true, 9 | imports: [ROUTER, NavComponentComponent, SpinnerComponent], 10 | 11 | template: ` 12 | 13 | 14 | `, 15 | }) 16 | export class AppComponent { 17 | title = 'Angular Validation Done Right!'; 18 | } 19 | -------------------------------------------------------------------------------- /src/app/app.routes.ts: -------------------------------------------------------------------------------- 1 | import { Routes } from '@angular/router'; 2 | import { SoloAddressFormComponent } from '@app/teaching-forms/solo-address-form-reactive-w-val/solo-address-form.component'; 3 | import { CompanyFormComponent } from "@app/company/company-form.component"; 4 | import { CompanyReactiveFormComponent } from "@app/company-reactive/company-form-reactive.component"; 5 | import { EmployeeFormComponent } from '@app/employee/employee-form.component'; 6 | import { EmployeeListComponent } from '@app/employee/employee-list.component'; 7 | import { PageLeaveGuard } from '@services'; 8 | import { SettingsComponent } from '@app/settings-component/settings.component'; 9 | 10 | 11 | /** Main application routes */ 12 | export const appRoutes: Routes = [ 13 | { 14 | path: '', 15 | pathMatch: 'full', 16 | redirectTo: 'company' 17 | }, 18 | { 19 | path: 'about', 20 | loadComponent: () => 21 | import('@app/teaching-forms/about/about.component').then(m => m.AboutComponent), 22 | title: 'About' 23 | }, 24 | { 25 | path: 'company', 26 | component: CompanyFormComponent, 27 | title: 'Company', 28 | canDeactivate: [PageLeaveGuard], 29 | }, 30 | { 31 | path: 'company-reactive', 32 | component: CompanyReactiveFormComponent, 33 | title: 'Company (Reactive)' 34 | }, 35 | { 36 | path: 'employees', 37 | component: EmployeeListComponent, 38 | title: 'Employees' 39 | }, 40 | { 41 | path: 'employees/:id', 42 | component: EmployeeFormComponent, 43 | title: 'Employee Form', 44 | canDeactivate: [PageLeaveGuard], 45 | }, 46 | { 47 | path: 'settings', 48 | component: SettingsComponent, 49 | title: 'Settings' 50 | }, 51 | { 52 | path: 'solo-address', 53 | component: SoloAddressFormComponent, 54 | title: 'Solo Address' 55 | }, 56 | ]; 57 | -------------------------------------------------------------------------------- /src/app/company-reactive/address-form-reactive.component.html: -------------------------------------------------------------------------------- 1 |
2 |
3 | 4 | 5 | 6 | {{ addressForm.controls.street.errors['error'] }} 7 | 8 | 9 | 10 | 11 | 12 | 13 |
14 | 15 |
16 | 17 | 18 | 19 | {{ addressForm.controls.city.errors['error'] }} 20 | 21 | 22 | 23 | 24 | 25 | 26 | {{ state.name }} 27 | 28 | 29 | 30 | {{ addressForm.controls.state.errors['error'] }} 31 | 32 | 33 |
34 | 35 |
36 | 37 | 38 | 39 | {{ addressForm.controls.postalCode.errors['error'] }} 40 | 41 | 42 |
43 |
44 | -------------------------------------------------------------------------------- /src/app/company-reactive/address-form-reactive.component.ts: -------------------------------------------------------------------------------- 1 | import { Component, Input, OnInit } from '@angular/core'; 2 | import { FormBuilder, NgForm } from '@angular/forms'; 3 | 4 | import { Address } from '@model'; 5 | import { addValidatorsToControls } from '@validation'; 6 | import { addressSyncValidationSuite } from '@validators'; 7 | import { REACTIVE_FORMS } from '@imports'; 8 | import { UsStates } from '@model'; 9 | 10 | interface Vm { 11 | street: string | null; 12 | street2: string | null; 13 | city: string | null; 14 | state: string | null; 15 | postalCode: string | null; 16 | } 17 | 18 | @Component({ 19 | selector: 'app-address-form', 20 | standalone: true, 21 | templateUrl: './address-form-reactive.component.html', 22 | imports: [REACTIVE_FORMS], 23 | }) 24 | export class AddressReactiveFormComponent implements OnInit { 25 | /** Name for the formGroup when added to the parent form. Defaults to 'address'. */ 26 | // eslint-disable-next-line @angular-eslint/no-input-rename 27 | @Input('name') formGroupName = 'address'; 28 | 29 | @Input() address?: Address; 30 | 31 | protected addressForm = this.fb.group({ 32 | street: '', 33 | street2: '', 34 | city: '', 35 | state: '', 36 | postalCode: '', 37 | }); 38 | 39 | hasStreet2 = false; 40 | 41 | states = UsStates; 42 | 43 | constructor(private fb: FormBuilder, private parent: NgForm) { 44 | addValidatorsToControls(this.addressForm.controls, addressSyncValidationSuite); 45 | } 46 | 47 | ngOnInit(): void { 48 | // Add this reactive form to the parent form 49 | // See Kara's AngularConnect 2017 talk: https://youtu.be/CD_t3m2WMM8?t=2150 50 | // Wait a tick to bypass ExpressionChangedAfterItHasBeenCheckedError for `ng-valid` 51 | setTimeout(() => { 52 | this.parent.form.addControl(this.formGroupName, this.addressForm); 53 | if (this.address) { 54 | // Populate controls 55 | this.addressForm.setValue(this.address); 56 | } 57 | }, 1); 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /src/app/company-reactive/company-form-reactive.component.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Company (Reactive) 6 | 7 | 8 | 9 | 10 | 11 |

Work Address

12 | 13 | 14 |
15 | 16 | 17 | 20 | 21 | 22 |
23 |
24 | -------------------------------------------------------------------------------- /src/app/company-reactive/company-form-reactive.component.ts: -------------------------------------------------------------------------------- 1 | import { Component } from '@angular/core'; 2 | import { NgForm } from '@angular/forms'; 3 | 4 | import { AddressReactiveFormComponent } from './address-form-reactive.component'; 5 | import { CompanyGeneralReactiveFormComponent } from './company-general-form-reactive.component'; 6 | 7 | import { Address, Company } from '@model'; 8 | import { CompanyFormValidationDemoService } from '@services/company-form-validation-demo.service'; 9 | import { FORMS } from '@imports'; 10 | 11 | @Component({ 12 | selector: 'app-company-form', 13 | standalone: true, 14 | templateUrl: './company-form-reactive.component.html', 15 | imports: [AddressReactiveFormComponent, CompanyGeneralReactiveFormComponent, FORMS] 16 | }) 17 | export class CompanyReactiveFormComponent { 18 | 19 | constructor(private demoService: CompanyFormValidationDemoService) { } 20 | 21 | company: Company = { 22 | id: '', 23 | legalName: '', 24 | workAddress: { 25 | street: '', 26 | street2: '', 27 | city: '', 28 | state: '', 29 | postalCode: '' 30 | } as Address 31 | }; 32 | 33 | /** DEMO: validate the company form and display aspects of it in the browser console */ 34 | showValidationState(ngForm: NgForm): void { 35 | // Reveal validation state at this form level and all the way down. 36 | ngForm?.form.markAllAsTouched(); 37 | this.demoService.demoReactive(ngForm); 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /src/app/company-reactive/company-general-form-reactive.component.html: -------------------------------------------------------------------------------- 1 |
2 |
3 | 4 | 5 | 6 | {{ generalForm.controls.legalName.errors['error'] }} 7 | 8 | 9 |
10 |
11 | 12 | 13 | 14 | {{ generalForm.controls.fein.errors['error'] }} 15 | 16 | 17 |
18 |
19 | -------------------------------------------------------------------------------- /src/app/company-reactive/company-general-form-reactive.component.ts: -------------------------------------------------------------------------------- 1 | import { Component, Inject, Input, OnInit, Optional } from '@angular/core'; 2 | import { FormBuilder, NgForm } from '@angular/forms'; 3 | 4 | import { addValidatorsToControls, VALIDATION_CONTEXT } from '@validation'; 5 | import { AppValidationContext, createCompanyAsyncValidationSuite, companySyncValidationSuite } from '@validators'; 6 | import { Company } from '@model'; 7 | import { formContainerViewProvider } from '@core'; 8 | import { REACTIVE_FORMS } from '@imports'; 9 | 10 | @Component({ 11 | selector: 'app-company-general-form', 12 | standalone: true, 13 | templateUrl: './company-general-form-reactive.component.html', 14 | viewProviders: [formContainerViewProvider], 15 | imports: [REACTIVE_FORMS] 16 | }) 17 | export class CompanyGeneralReactiveFormComponent implements OnInit { 18 | @Input() company?: Company; 19 | 20 | protected generalForm = this.fb.group({ 21 | legalName: '', 22 | fein: '', 23 | }); 24 | 25 | constructor( 26 | @Optional() @Inject(VALIDATION_CONTEXT) validationContext: AppValidationContext, 27 | private fb: FormBuilder, 28 | private parent: NgForm 29 | ) { 30 | addValidatorsToControls( 31 | this.generalForm.controls, 32 | companySyncValidationSuite, 33 | createCompanyAsyncValidationSuite, 34 | () => this.generalForm.value, 35 | validationContext, 36 | ); 37 | 38 | // because change to fein can invalidate legalName ... 39 | this.generalForm.controls.fein.valueChanges.subscribe(_ => 40 | // wait a tick before updating legalName 41 | setTimeout(() => this.generalForm.controls.legalName.updateValueAndValidity()) 42 | ); 43 | 44 | } 45 | 46 | ngOnInit(): void { 47 | // Add this reactive form to the parent form 48 | // See Kara's AngularConnect 2017 talk: https://youtu.be/CD_t3m2WMM8?t=2150 49 | // Wait a tick to bypass ExpressionChangedAfterItHasBeenCheckedError for `ng-valid` 50 | setTimeout(() => { 51 | this.parent.form.addControl('general', this.generalForm); 52 | if (this.company) { 53 | // Populate controls 54 | this.generalForm.setValue({ 55 | legalName: this.company.legalName || '', 56 | fein: this.company.fein || '', 57 | }); 58 | } 59 | }, 1); 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /src/app/company/company-form.component.html: -------------------------------------------------------------------------------- 1 |
2 | 3 | 4 | 5 | Company 6 | 7 | 8 | 9 | 10 | 11 |

Work Address

12 | 13 | 14 |
15 | 16 | 17 | 19 | 20 | 21 |
22 |
23 | -------------------------------------------------------------------------------- /src/app/company/company-form.component.spec.ts: -------------------------------------------------------------------------------- 1 | import { FormGroup } from '@angular/forms'; 2 | import { ComponentFixture, fakeAsync, TestBed, tick, waitForAsync } from '@angular/core/testing'; 3 | import { NoopAnimationsModule } from '@angular/platform-browser/animations'; 4 | 5 | import { BehaviorSubject, of } from 'rxjs'; 6 | 7 | import { Address, Company } from '@model'; 8 | import { appValidationContextProvider } from '@validators'; 9 | import { CompanyFormValidationDemoService } from '../services/company-form-validation-demo.service'; 10 | import { CompanyFormComponent } from './company-form.component'; 11 | import { DataService } from '@services'; 12 | import { validationSuiteProviders } from '@validators'; 13 | 14 | describe('CompanyFormComponent', () => { 15 | let component: CompanyFormComponent; 16 | let fixture: ComponentFixture; 17 | 18 | beforeEach(waitForAsync(() => { 19 | TestBed.configureTestingModule({ 20 | imports: [ 21 | NoopAnimationsModule, 22 | ], 23 | providers: [ 24 | appValidationContextProvider, 25 | CompanyFormValidationDemoService, 26 | { provide: DataService, useClass: TestDataService }, 27 | validationSuiteProviders, 28 | ] 29 | }).compileComponents(); 30 | })); 31 | 32 | beforeEach(waitForAsync(async () => { 33 | fixture = TestBed.createComponent(CompanyFormComponent); 34 | component = fixture.componentInstance; 35 | fixture.detectChanges(); 36 | // wait for NgForm to be populated by detectChanges. 37 | })); 38 | 39 | it('should compile', () => { 40 | expect(component).toBeTruthy(); 41 | }); 42 | 43 | it('should have a populated form control', () => { 44 | const controls = component.form!.controls; 45 | expect(Object.keys(controls).length).toBeGreaterThan(1); 46 | }); 47 | 48 | it('should have company fields validated with the company modelType', () => { 49 | const controls = component.form!.controls; 50 | expect(controls['legalName']._validationMetadata?.modelType).toBe('company'); 51 | expect(controls['fein']._validationMetadata?.modelType).toBe('company'); 52 | }) 53 | 54 | it('should have company.workAddress fields validated with the address modelType', () => { 55 | const workAddressGroup = component.form!.controls['workAddress'] as FormGroup; 56 | const controls = workAddressGroup?.controls; 57 | Object.keys(controls).forEach(key => { 58 | expect(controls[key]._validationMetadata?.modelType).toBe('address'); 59 | }) 60 | }); 61 | }); 62 | 63 | class TestDataService { 64 | companySubject = new BehaviorSubject>({ 65 | legalName: 'Test Name', 66 | fein: '', 67 | workAddress: {} as Address 68 | }); 69 | company$ = this.companySubject.asObservable(); 70 | saveCompanyData = jasmine.createSpy('saveCompanyData').and.returnValue(of(true)); 71 | } 72 | -------------------------------------------------------------------------------- /src/app/company/company-form.component.ts: -------------------------------------------------------------------------------- 1 | import { Component, ViewChild } from '@angular/core'; 2 | import { NgForm } from '@angular/forms'; 3 | import { tap } from 'rxjs/operators'; 4 | 5 | // // With widgets 6 | import { AddressFormComponent } from '@app/address/address-form.component'; 7 | import { CompanyGeneralFormComponent } from './company-general-form.component'; 8 | 9 | // No widgets 10 | // import { AddressFormComponent } from './address-form-no-widget/address-form.component'; 11 | // import { CompanyGeneralFormComponent } from './company-general-form-no-widget.component'; 12 | 13 | import { Company } from '@model'; 14 | import { CompanyFormValidationDemoService } from '@services/company-form-validation-demo.service'; 15 | import { CompanyViewService } from './company-view.service'; 16 | import { FORMS } from '@imports'; 17 | 18 | @Component({ 19 | selector: 'app-company-form', 20 | standalone: true, 21 | templateUrl: './company-form.component.html', 22 | imports: [AddressFormComponent, CompanyGeneralFormComponent, FORMS], 23 | }) 24 | export class CompanyFormComponent { 25 | /** The NgForm, exposed for testing only. */ 26 | @ViewChild('form') form!: NgForm; 27 | 28 | constructor( 29 | private viewService: CompanyViewService, 30 | private demoService: CompanyFormValidationDemoService, 31 | ) { } 32 | 33 | vm!: Company; 34 | vm$ = this.viewService.company$.pipe( 35 | tap(vm => this.vm = vm!) // access the view model from within the class 36 | ); 37 | 38 | canLeave() { 39 | return this.viewService.saveCompanyVm(this.vm); 40 | } 41 | 42 | /** DEMO: validate the company form and display aspects of it in the browser console */ 43 | showValidationState(ngForm: NgForm): void { 44 | // Reveal validation state at this form level and all the way down. 45 | ngForm?.form.markAllAsTouched(); 46 | this.demoService.demoTD(ngForm.controls, this.vm!); 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /src/app/company/company-general-form.component.html: -------------------------------------------------------------------------------- 1 |
2 | 3 |
4 |
5 | 6 |
7 | -------------------------------------------------------------------------------- /src/app/company/company-general-form.component.spec.ts: -------------------------------------------------------------------------------- 1 | import { waitForAsync, ComponentFixture, TestBed } from '@angular/core/testing'; 2 | import { NoopAnimationsModule } from '@angular/platform-browser/animations'; 3 | 4 | import { CompanyGeneralFormComponent } from './company-general-form.component'; 5 | import { validationSuiteProviders } from '@validators'; 6 | 7 | describe('CompanyGeneralFormComponent', () => { 8 | let component: CompanyGeneralFormComponent; 9 | let fixture: ComponentFixture; 10 | 11 | beforeEach(waitForAsync(() => { 12 | TestBed.configureTestingModule({ 13 | imports: [ NoopAnimationsModule ], 14 | providers: [ validationSuiteProviders ] 15 | }).compileComponents(); 16 | })); 17 | 18 | beforeEach(() => { 19 | fixture = TestBed.createComponent(CompanyGeneralFormComponent); 20 | component = fixture.componentInstance; 21 | fixture.detectChanges(); 22 | }); 23 | 24 | it('should compile', () => { 25 | expect(component).toBeTruthy(); 26 | }); 27 | }); 28 | -------------------------------------------------------------------------------- /src/app/company/company-general-form.component.ts: -------------------------------------------------------------------------------- 1 | import { Component, Input, ViewChild } from '@angular/core'; 2 | 3 | import { Company } from '@model'; 4 | import { formContainerViewProvider } from '@core'; 5 | import { FORMS } from '@imports'; 6 | import { InputTextComponent } from '@app/widgets'; 7 | 8 | @Component({ 9 | selector: 'app-company-general-form', 10 | standalone: true, 11 | imports: [FORMS], 12 | templateUrl: './company-general-form.component.html', 13 | viewProviders: [formContainerViewProvider], 14 | }) 15 | export class CompanyGeneralFormComponent { 16 | @Input() vm?: Partial; 17 | @ViewChild('legalName') legalNameComponent!: InputTextComponent; 18 | 19 | /** Revalidate LegalName, updating its error message, when FEIN changes. 20 | * A change to FEIN should invalidate the Legal Name if that name does not match the registered IRS name. 21 | * 22 | * Problem: Angular won't automatically revalidate one field when another changes. 23 | * A model group level validation won't help; can't use that to control the legal name message output 24 | * 25 | * Solution: when FEIN changes, force revalidation of Legal Name 26 | */ 27 | protected feinChanged(_fein: string | null) { 28 | // console.log('fein changed to ' + _fein); 29 | const control = this.legalNameComponent.control; 30 | control?.markAsTouched(); // ensure display 31 | setTimeout(() => { 32 | // wait one tick for ngModel to update the model, then re-validate. 33 | control?.updateValueAndValidity(); 34 | }); 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /src/app/company/company-view.service.ts: -------------------------------------------------------------------------------- 1 | import { Injectable } from '@angular/core'; 2 | import { Observable } from 'rxjs'; 3 | import { filter, map, take } from 'rxjs/operators'; 4 | 5 | import { areDifferent, deepClone } from '@utils'; 6 | import { Company } from '@model'; 7 | import { DataService } from '@services'; 8 | 9 | @Injectable({ providedIn: 'root'}) 10 | export class CompanyViewService { 11 | company$ = this.dataService.company$; 12 | constructor(private dataService: DataService) { } 13 | 14 | /** Build the CompanyVm for the current Company 15 | * @returns a terminating observable of a VM for that Company if it exists 16 | * else terminating observable of null. 17 | */ 18 | getCompanyVm(): Observable { 19 | return this.dataService.company$.pipe( 20 | filter(co => co != null), 21 | take(1), 22 | map(co => deepClone(co)) 23 | ); 24 | } 25 | 26 | /** Save Company changes in the ViewModel, if there are any */ 27 | saveCompanyVm(vm: Company | null): Observable | boolean { 28 | const { company } = this.dataService.cacheNow(); 29 | const newCo = { ...company, ...vm } as Company; 30 | if (areDifferent(company, vm)) { 31 | return this.dataService.saveCompanyData({ company: newCo }); 32 | } else { 33 | return true; // no change 34 | } 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /src/app/core/form-container-view-provider.ts: -------------------------------------------------------------------------------- 1 | import { Optional, Provider } from '@angular/core'; 2 | import { ControlContainer, NgForm, NgModelGroup } from '@angular/forms'; 3 | 4 | /** 5 | * Provide a ControlContainer to a form component from the 6 | * nearest parent NgModelGroup (preferred) or NgForm. 7 | * 8 | * Required for Reactive Forms as well (unless you write CVA) 9 | * 10 | * @example 11 | * ``` 12 | * @Component({ 13 | * ... 14 | * viewProviders[ formContainerViewProvider ] 15 | * }) 16 | * ``` 17 | * @see Kara's AngularConnect 2017 talk: https://youtu.be/CD_t3m2WMM8?t=1826 18 | * 19 | * Without this provider 20 | * - Controls are not registered with parent NgForm or NgModelGroup 21 | * - Form-level flags say "untouched" and "valid" 22 | * - No form-level validation roll-up 23 | * - Controls still validate, update model, and update their statuses 24 | * - If within NgForm, no compiler error because ControlContainer is optional for ngModel 25 | * 26 | * Note: if the Form Component that uses this Provider 27 | * is not within a Form or NgModelGroup, the provider returns `null` 28 | * resulting in an error, something like 29 | * ``` 30 | * preview-fef3604083950c709c52b.js:1 ERROR Error: 31 | * ngModelGroup cannot be used with a parent formGroup directive. 32 | *``` 33 | */ 34 | export const formContainerViewProvider: Provider = { 35 | provide: ControlContainer, 36 | useFactory: formContainerViewProviderFactory, 37 | deps: [ 38 | [new Optional(), NgForm], 39 | [new Optional(), NgModelGroup] 40 | ] 41 | }; 42 | 43 | export function formContainerViewProviderFactory( 44 | ngForm: NgForm, ngModelGroup: NgModelGroup 45 | ) { 46 | return ngModelGroup ?? ngForm ?? null; 47 | } 48 | -------------------------------------------------------------------------------- /src/app/core/imports.ts: -------------------------------------------------------------------------------- 1 | import { CommonModule } from '@angular/common'; 2 | import { FormsModule, ReactiveFormsModule } from '@angular/forms'; 3 | import { RouterModule } from '@angular/router'; 4 | 5 | import { MatButtonModule } from '@angular/material/button'; 6 | import { MatCardModule } from '@angular/material/card'; 7 | import { MatInputModule } from '@angular/material/input'; 8 | import { MatRadioModule } from '@angular/material/radio'; 9 | import { MatSelectModule } from '@angular/material/select'; 10 | 11 | import { InputErrorComponent, InputSelectComponent, InputTextComponent } from '@app/widgets'; 12 | import { FormFieldNgModelDirective } from '@validation/form-field-ng-model.directive'; 13 | import { FormValidationScopeDirective } from '@app/validation/form-validation-scope.directive'; 14 | 15 | /** Imports for components referencing just the Common Module */ 16 | export const COMMON = [CommonModule]; 17 | 18 | /** Standard imports for (almost) every Template-Driven forms component in this app. */ 19 | export const LIST = [ 20 | CommonModule, 21 | MatButtonModule, MatCardModule, MatInputModule, MatRadioModule, MatSelectModule, 22 | ]; 23 | 24 | /** Standard imports for (almost) every Template-Driven forms component in this app. */ 25 | export const FORMS = [ 26 | CommonModule, 27 | FormFieldNgModelDirective, FormValidationScopeDirective, 28 | InputErrorComponent, InputSelectComponent, InputTextComponent, 29 | MatButtonModule, MatCardModule, MatInputModule, MatRadioModule, MatSelectModule, 30 | FormsModule, 31 | ]; 32 | /** Standard imports for (almost) every Reactive Forms component in this app. */ 33 | export const REACTIVE_FORMS = [ 34 | CommonModule, 35 | MatButtonModule, MatCardModule, MatInputModule, MatRadioModule, MatSelectModule, 36 | ReactiveFormsModule 37 | ]; 38 | 39 | /** Imports for components referencing the Angular Router */ 40 | export const ROUTER = [RouterModule]; 41 | -------------------------------------------------------------------------------- /src/app/core/index.ts: -------------------------------------------------------------------------------- 1 | export * from './form-container-view-provider'; 2 | export * from './imports'; 3 | export * from './utils'; 4 | -------------------------------------------------------------------------------- /src/app/core/spinner/spinner.component.scss: -------------------------------------------------------------------------------- 1 | .spinner-container { 2 | display: flex; 3 | flex-grow: 1; 4 | width: 100%; 5 | height: 100%; 6 | position: fixed; 7 | top: 0; 8 | left: 0; 9 | z-index: 100; 10 | 11 | .spinner-shade { 12 | display: flex; 13 | width: 100%; 14 | height: 100%; 15 | background-color: rgba(white, 0.6); 16 | z-index: 101; 17 | } 18 | 19 | .spinner-box { 20 | display: flex; 21 | align-content: center; 22 | justify-content: center; 23 | flex-direction: column; 24 | margin: auto; 25 | height: 200px; 26 | 27 | .spinner-label { 28 | width: 300px; 29 | text-align: center; 30 | padding: 1rem; 31 | 32 | h2 { 33 | width: 100%; 34 | text-align: center; 35 | } 36 | } 37 | } 38 | 39 | .spinner-animation { 40 | width: 100px; 41 | margin: auto; 42 | flex: 1; 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /src/app/core/spinner/spinner.component.ts: -------------------------------------------------------------------------------- 1 | import { Component } from '@angular/core'; 2 | import { COMMON } from '@imports'; 3 | import { BusyService, BusyState } from '@services'; 4 | import { Observable } from 'rxjs'; 5 | import { tap } from 'rxjs/operators'; 6 | 7 | /* 8 | Spinner to display during long operations. 9 | The outer div blocks the entire screen, so user cannot input while app is busy. 10 | The inner div shows the spinner after a delay, so it won't show immediately. 11 | The captures keyboard events but stays offscreen. 12 | */ 13 | @Component({ 14 | selector: 'app-spinner', 15 | standalone: true, 16 | template: ` 17 | 18 |
19 |
20 |
21 |
22 | 23 |
24 |
25 |

{{ busy.message }}

26 |
27 |
28 |
29 | 35 |
36 |
37 | `, 38 | styleUrls: ['./spinner.component.scss'], 39 | imports: [COMMON] 40 | }) 41 | export class SpinnerComponent { 42 | /** MS to delay before showing spinner and message. Static prop for ease of testing */ 43 | static defaultDelayMs = 1000; 44 | 45 | busyState$: Observable; 46 | 47 | /** True when should hide the spinner and message */ 48 | hideSpinner = true; 49 | 50 | private timeoutId: any; 51 | 52 | constructor(public busyService: BusyService) { 53 | this.busyState$ = busyService.busyState$.pipe(tap((state) => this.setSpinnerVisibility(state))); 54 | } 55 | 56 | // Manage delayable display of spinner and message when state changes 57 | private setSpinnerVisibility(state: BusyState) { 58 | if (state.isBusy) { 59 | if (state.delay) { 60 | // expose spinner after delay expires (if not previously delayed) 61 | if (!this.timeoutId) { 62 | this.timeoutId = setTimeout( 63 | () => (this.hideSpinner = false), 64 | SpinnerComponent.defaultDelayMs 65 | ); 66 | } 67 | } else { 68 | // No delay. Expose spinner now and cancel pending delay (if any) 69 | clearTimeout(this.timeoutId); 70 | this.hideSpinner = false; 71 | } 72 | } else { 73 | // No longer busy. Hide spinner now and cancel pending delay (if any) 74 | clearTimeout(this.timeoutId); 75 | this.hideSpinner = true; 76 | this.timeoutId = undefined; // can delay next time. 77 | } 78 | } 79 | } 80 | -------------------------------------------------------------------------------- /src/app/core/utils/guid.ts: -------------------------------------------------------------------------------- 1 | /** The empty GUID, result of new Guid() */ 2 | export const EMPTY_GUID = '00000000000000000000000000000000'; 3 | 4 | /** 5 | * Creates a pseudo-Guid (globally unique identifier) as 32 character string 6 | * whose trailing 6 bytes (12 hex digits) are time-based. 7 | * Also knows as a "GuidComb". 8 | * Start either with the given getTime() value, seedTime, 9 | * or get the current time in ms. 10 | * 11 | * @param seed {number} - optional seed for reproducible time-part for testing 12 | */ 13 | export function getGuid(seed?: number) { 14 | // Each new Guid is greater than next if more than 1ms passes 15 | // See http://thatextramile.be/blog/2009/05/using-the-guidcomb-identifier-strategy 16 | // Based on breeze.core.getUuid which is based on this StackOverflow answer 17 | // http://stackoverflow.com/a/2117523/200253 18 | // 19 | // Convert time value to hex: n.toString(16) 20 | // Make sure it is 6 bytes long: ('00'+ ...).slice(-12) ... from the rear 21 | // Replace LAST 6 bytes (12 hex digits) of regular Guid (that's where they sort in a Db) 22 | // 23 | // Play with this in jsFiddle: http://jsfiddle.net/wardbell/qS8aN/ 24 | const timePart = ('00' + (seed ?? new Date().getTime()).toString(16)).slice(-12); 25 | return ( 26 | 'xxxxxxxxxxxx4xxxyxxx'.replace(/[xy]/g, function (c) { 27 | const r = (Math.random() * 16) | 0, 28 | v = c === 'x' ? r : (r & 0x3) | 0x8; 29 | return v.toString(16); 30 | }) + timePart 31 | ); 32 | } 33 | -------------------------------------------------------------------------------- /src/app/core/utils/index.ts: -------------------------------------------------------------------------------- 1 | export * from './guid'; 2 | export * from './utils'; 3 | -------------------------------------------------------------------------------- /src/app/core/utils/utils.ts: -------------------------------------------------------------------------------- 1 | /** Deep clone an object (assumes no circularities) */ 2 | export function deepClone(obj: T | null | undefined) { 3 | return obj == null ? obj : JSON.parse(JSON.stringify(obj)); 4 | } 5 | 6 | /** Interface for an object that can be indexed with a string key */ 7 | export interface Indexable { 8 | [key: string]: T; 9 | } 10 | 11 | /** Return true if the two objects differ. A DEEP comparison using JSON.stringify. 12 | * Not forgiving of irrelevant differences such as property order and null/undefined properties. 13 | * Good enough for this demo app. 14 | * @param objectA object with potentially new or changed values 15 | * @param objectB, presumably an older version of the object. 16 | * @returns true if object A differs from object B 17 | */ 18 | export function areDifferent(objectA: T, objectB: T): boolean { 19 | return JSON.stringify(objectA) !== JSON.stringify(objectB); 20 | } 21 | -------------------------------------------------------------------------------- /src/app/employee/employee-form.component.ts: -------------------------------------------------------------------------------- 1 | import { Component } from '@angular/core'; 2 | import { RouterModule } from '@angular/router'; 3 | 4 | import { AddressFormComponent } from '@app/address/address-form.component'; 5 | import { EmployeeViewService, employeeTypes } from './employee-view.service'; 6 | import { FORMS } from '@imports'; 7 | 8 | @Component({ 9 | selector: 'app-employee-form', 10 | standalone: true, 11 | template: ` 12 | 13 | arrow_back 14 | Employees 15 | 16 | 17 |
18 | 19 | 20 | 21 | {{vm.name || 'The Employee'}} 22 | 23 | 24 | 25 |
26 | 27 | 28 |
29 |

Home Address

30 | 31 |
32 | 33 |
34 |
35 | `, 36 | imports: [AddressFormComponent, FORMS, RouterModule], 37 | }) 38 | export class EmployeeFormComponent { 39 | constructor(private viewService: EmployeeViewService) { } 40 | 41 | employeeTypes = employeeTypes; 42 | vm$ = this.viewService.getEmployeeVm(); 43 | 44 | /** Save Employee changes, if there are any, when user navigates away. */ 45 | canLeave() { 46 | return this.viewService.saveEmployeeVm(this.vm$); 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /src/app/employee/employee-list.component.ts: -------------------------------------------------------------------------------- 1 | import { Component } from '@angular/core'; 2 | import { RouterModule } from '@angular/router'; 3 | import { EmployeeViewService } from './employee-view.service'; 4 | import { LIST } from '@imports'; 5 | 6 | @Component({ 7 | selector: 'app-ee-list', 8 | standalone: true, 9 | template: ` 10 |
11 | 12 | 13 | 14 | Employees 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 |
{{ ee.name }}
23 | 24 | No Employees in this company 25 | 26 |
27 | 28 |
29 |
30 | 31 | `, 32 | imports: [LIST, RouterModule], 33 | }) 34 | export class EmployeeListComponent { 35 | constructor( private viewService: EmployeeViewService) { } 36 | 37 | employees$ = this.viewService.employees$; 38 | } 39 | -------------------------------------------------------------------------------- /src/app/employee/employee-view.service.ts: -------------------------------------------------------------------------------- 1 | import { Injectable } from '@angular/core'; 2 | import { Router } from '@angular/router'; 3 | import { concatMap, Observable, of } from 'rxjs'; 4 | import { filter, map, shareReplay, take, withLatestFrom } from 'rxjs/operators'; 5 | 6 | import { areDifferent, deepClone } from '@utils'; 7 | import { Employee, EmployeeType} from '@model'; 8 | import { DataService } from '@services'; 9 | import { SelectOption } from '@app/widgets/interfaces'; 10 | 11 | export const employeeTypes: SelectOption[] = [ 12 | { name: 'Full Time', value: EmployeeType.FullTime }, 13 | { name: 'Part Time', value: EmployeeType.PartTime }, 14 | { name: '1099 Contractor', value: EmployeeType.Contractor } 15 | ]; 16 | 17 | @Injectable({ providedIn: 'root'}) 18 | export class EmployeeViewService { 19 | employees$ = this.dataService.employees$; 20 | constructor( 21 | private dataService: DataService, 22 | private router: Router, 23 | ) { } 24 | 25 | /** Build the EmployeeVm for the current EE (identified by the id in the active route). 26 | * @returns a terminating observable of a VM of that EE if it exists 27 | * else terminating observable of null. 28 | * If null, also navigates to the EE page because that's where you must go. 29 | * Beware: ShareReplay ensures this observable always emits the same ViewModel (or null) instance. 30 | */ 31 | getEmployeeVm(): Observable { 32 | const eeId = getIdFromUrl(this.router); 33 | return this.dataService.company$.pipe( 34 | filter(co => co != null), // wait for current company to be loaded 35 | take(1), 36 | withLatestFrom(this.dataService.employees$), 37 | map(([_company, employees]) => { 38 | const ee = employees.find(e => e.id == eeId); 39 | if (ee) { 40 | return deepClone(ee); 41 | } else { 42 | this.router.navigateByUrl('/employees'); 43 | return null as Employee | null 44 | } 45 | }), 46 | shareReplay({bufferSize: 1, refCount: true }) 47 | ); 48 | } 49 | 50 | /** Save Employee changes in the ViewModel, if there are any */ 51 | saveEmployeeVm(vm$: Observable): Observable | boolean { 52 | return vm$.pipe( 53 | take(1), 54 | concatMap(vm => { 55 | const eeId = vm?.id; 56 | if (eeId) { 57 | const { employees: oldEmployees } = this.dataService.cacheNow(); 58 | const oldEe = oldEmployees.find(e => e.id === eeId); 59 | if (areDifferent(oldEe, vm)) { 60 | const employees: Employee[] = oldEmployees.map(e => e.id === eeId ? {...vm!} : e ); 61 | return this.dataService.saveCompanyData({ employees }); 62 | } 63 | } 64 | return of(true); // no change 65 | }) 66 | ) 67 | } 68 | } 69 | 70 | function getIdFromUrl(router: Router) { 71 | const match = router.url.match(/([^/.]*)$/); 72 | return match ? match[1] : null; 73 | } 74 | -------------------------------------------------------------------------------- /src/app/model/address.ts: -------------------------------------------------------------------------------- 1 | import { Indexable } from '@utils'; 2 | 3 | export interface Address extends Indexable { 4 | street: string | null; 5 | street2: string | null; 6 | city: string | null; 7 | state: string | null; 8 | postalCode:string | null; 9 | verified?: boolean; 10 | } 11 | -------------------------------------------------------------------------------- /src/app/model/company.ts: -------------------------------------------------------------------------------- 1 | import { Address } from './address'; 2 | import { getGuid, Indexable } from '@utils'; 3 | 4 | export interface Company extends Indexable { 5 | id: string; 6 | 7 | /** Federal Employer Identification Number */ 8 | fein?: string; 9 | legalName?: string; 10 | workAddress: Address; 11 | } 12 | 13 | export function createCompany(name?: string): Company { 14 | return { 15 | id: getGuid(), 16 | legalName: name, 17 | workAddress: {} as Address 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /src/app/model/employee-tax.ts: -------------------------------------------------------------------------------- 1 | export interface EmployeeTax { 2 | readonly id: string; 3 | readonly companyId: string; 4 | 5 | /** Id of the Employee this tax belongs to */ 6 | readonly employeeId: string; 7 | 8 | // #region Set at creation by the tax service 9 | 10 | /** The unique identifier of the tax code. ex: FE0000-003 */ 11 | readonly taxCode: string; 12 | 13 | /** The tax code name, mainly used for display reasons */ 14 | readonly name: string; 15 | 16 | /** The state code. ex PA; null for federal taxes */ 17 | readonly state: string | null; 18 | 19 | /** A code that describes if the tax is on the Federal, State, County, City or School district level */ 20 | readonly taxType: TaxType; 21 | 22 | // #endregion Set at creation by the tax service 23 | 24 | /** Single, Married, Head of Household. An api driven field. Ex: Married = M */ 25 | filingStatus?: FilingStatus; 26 | 27 | /** If the employee is exempt from paying this tax */ 28 | isExempt: boolean; 29 | 30 | /** Federal or State withholding allowance (a number) */ 31 | withholdingAllowance: number; 32 | 33 | /** Fixed amount of extra withholding (dollars) */ 34 | extraWithholding?: number; 35 | } 36 | 37 | /** Filing Status enum */ 38 | export enum FilingStatus { 39 | Single = 'S', 40 | Married = 'M', 41 | HeadOfHousehold = 'H' 42 | } 43 | 44 | /** Name/Value pairs for the filing status. The name is a label. */ 45 | export const FilingStatuses = [ 46 | { name: 'Single or married filing as single', value: 'S' }, 47 | { name: 'Married', value: 'M' }, 48 | { name: 'Head of household', value: 'H' } 49 | ] 50 | 51 | /** TaxType enum: Federal, State, County, City or School district level */ 52 | export enum TaxType { 53 | Federal = 'FD', 54 | State = 'ST', 55 | County = 'CN', 56 | City = 'CT', 57 | SchoolDistrict = 'SD' 58 | } 59 | -------------------------------------------------------------------------------- /src/app/model/employee.ts: -------------------------------------------------------------------------------- 1 | import { Address } from './address'; 2 | 3 | export interface Employee extends Address { 4 | // Personal Address fields come from Address base interface 5 | id: string; 6 | companyId: string; 7 | 8 | birthDate: string; 9 | email: string; 10 | employeeStatus: EmployeeStatus; 11 | employeeType: EmployeeType; 12 | hireDate: string; 13 | name: string; 14 | } 15 | 16 | export enum EmployeeStatus { 17 | Active = 'Active', 18 | Terminated = 'Terminated', 19 | } 20 | 21 | export enum EmployeeType { 22 | FullTime = 'FullTime', 23 | PartTime = 'PartTime', 24 | Contractor = '1099 Contractor' 25 | } 26 | -------------------------------------------------------------------------------- /src/app/model/entity-cache.ts: -------------------------------------------------------------------------------- 1 | import { Company } from './company'; 2 | import { Employee } from './employee'; 3 | import { EmployeeTax } from './employee-tax'; 4 | 5 | export class Cache { 6 | currentCompanyId: string = ''; 7 | company?: Company; 8 | employees: Employee[] = []; 9 | employeeTaxes: EmployeeTax[] = []; 10 | loading = false; 11 | } 12 | -------------------------------------------------------------------------------- /src/app/model/index.ts: -------------------------------------------------------------------------------- 1 | export * from './address'; 2 | export * from './company'; 3 | export * from './employee'; 4 | export * from './employee-tax'; 5 | export * from './entity-cache'; 6 | export * from './us-states'; 7 | -------------------------------------------------------------------------------- /src/app/model/us-states.ts: -------------------------------------------------------------------------------- 1 | /** Map of US state names to their abbreviations */ 2 | export const UsStates = [ 3 | {name: 'Alabama', abbreviation: 'AL'}, 4 | {name: 'Alaska', abbreviation: 'AK'}, 5 | {name: 'American Samoa', abbreviation: 'AS', disabled: true}, 6 | {name: 'Arizona', abbreviation: 'AZ'}, 7 | {name: 'Arkansas', abbreviation: 'AR'}, 8 | {name: 'California', abbreviation: 'CA'}, 9 | {name: 'Colorado', abbreviation: 'CO'}, 10 | {name: 'Connecticut', abbreviation: 'CT'}, 11 | {name: 'Delaware', abbreviation: 'DE'}, 12 | {name: 'District Of Columbia', abbreviation: 'DC'}, 13 | {name: 'Federated States Of Micronesia', abbreviation: 'FM', disabled: true}, 14 | {name: 'Florida', abbreviation: 'FL'}, 15 | {name: 'Georgia', abbreviation: 'GA'}, 16 | {name: 'Guam', abbreviation: 'GU'}, 17 | {name: 'Hawaii', abbreviation: 'HI'}, 18 | {name: 'Idaho', abbreviation: 'ID'}, 19 | {name: 'Illinois', abbreviation: 'IL'}, 20 | {name: 'Indiana', abbreviation: 'IN'}, 21 | {name: 'Iowa', abbreviation: 'IA'}, 22 | {name: 'Kansas', abbreviation: 'KS'}, 23 | {name: 'Kentucky', abbreviation: 'KY'}, 24 | {name: 'Louisiana', abbreviation: 'LA'}, 25 | {name: 'Maine', abbreviation: 'ME'}, 26 | {name: 'Marshall Islands', abbreviation: 'MH', disabled: true}, 27 | {name: 'Maryland', abbreviation: 'MD'}, 28 | {name: 'Massachusetts', abbreviation: 'MA'}, 29 | {name: 'Michigan', abbreviation: 'MI'}, 30 | {name: 'Minnesota', abbreviation: 'MN'}, 31 | {name: 'Mississippi', abbreviation: 'MS'}, 32 | {name: 'Missouri', abbreviation: 'MO'}, 33 | {name: 'Montana', abbreviation: 'MT'}, 34 | {name: 'Nebraska', abbreviation: 'NE'}, 35 | {name: 'Nevada', abbreviation: 'NV'}, 36 | {name: 'New Hampshire', abbreviation: 'NH'}, 37 | {name: 'New Jersey', abbreviation: 'NJ'}, 38 | {name: 'New Mexico', abbreviation: 'NM'}, 39 | {name: 'New York', abbreviation: 'NY'}, 40 | {name: 'North Carolina', abbreviation: 'NC'}, 41 | {name: 'North Dakota', abbreviation: 'ND'}, 42 | {name: 'Northern Mariana Islands', abbreviation: 'MP', disabled: true}, 43 | {name: 'Ohio', abbreviation: 'OH'}, 44 | {name: 'Oklahoma', abbreviation: 'OK'}, 45 | {name: 'Oregon', abbreviation: 'OR'}, 46 | {name: 'Palau', abbreviation: 'PW', disabled: true}, 47 | {name: 'Pennsylvania', abbreviation: 'PA'}, 48 | {name: 'Puerto Rico', abbreviation: 'PR'}, 49 | {name: 'Rhode Island', abbreviation: 'RI'}, 50 | {name: 'South Carolina', abbreviation: 'SC'}, 51 | {name: 'South Dakota', abbreviation: 'SD'}, 52 | {name: 'Tennessee', abbreviation: 'TN'}, 53 | {name: 'Texas', abbreviation: 'TX'}, 54 | {name: 'Utah', abbreviation: 'UT'}, 55 | {name: 'Vermont', abbreviation: 'VT'}, 56 | {name: 'Virgin Islands', abbreviation: 'VI'}, 57 | {name: 'Virginia', abbreviation: 'VA'}, 58 | {name: 'Washington', abbreviation: 'WA'}, 59 | {name: 'West Virginia', abbreviation: 'WV'}, 60 | {name: 'Wisconsin', abbreviation: 'WI'}, 61 | {name: 'Wyoming', abbreviation: 'WY'} 62 | ]; 63 | -------------------------------------------------------------------------------- /src/app/nav-component/nav-component.component.html: -------------------------------------------------------------------------------- 1 | 2 | 6 | 7 | 8 | homeCompany 9 | groupEmployees 10 | settingsSettings 11 |
12 |

Teaching

13 | 18 |
19 |
20 | 21 | 22 | 31 |

NgConf 2022 Validation

32 |
33 | 34 |
35 | 36 |
37 |
38 |
39 | -------------------------------------------------------------------------------- /src/app/nav-component/nav-component.component.scss: -------------------------------------------------------------------------------- 1 | .sidenav-container { 2 | height: 100%; 3 | } 4 | 5 | .sidenav { 6 | width: 200px; 7 | } 8 | 9 | .sidenav .mat-toolbar { 10 | background: inherit; 11 | } 12 | 13 | .material-icons { 14 | margin-right: 0.2rem; 15 | } 16 | 17 | .mat-toolbar.mat-primary { 18 | position: sticky; 19 | top: 0; 20 | z-index: 1; 21 | } 22 | 23 | mat-nav-list { 24 | margin-top: 2rem; 25 | } 26 | 27 | #content { 28 | margin: 0.5rem 0 0 0.5rem; 29 | } 30 | 31 | #menu-button { 32 | margin-right: 0.5rem; 33 | } 34 | 35 | hr { 36 | margin: 1rem 1.5rem 37 | } 38 | 39 | h2 { 40 | color: grey; 41 | font-size: 18px; 42 | margin-left: 1.2rem; 43 | } 44 | 45 | .other .mat-list-item { 46 | color: grey; 47 | font-size: 90%; 48 | } 49 | -------------------------------------------------------------------------------- /src/app/nav-component/nav-component.component.spec.ts: -------------------------------------------------------------------------------- 1 | import { LayoutModule } from '@angular/cdk/layout'; 2 | import { waitForAsync, ComponentFixture, TestBed } from '@angular/core/testing'; 3 | import { NoopAnimationsModule } from '@angular/platform-browser/animations'; 4 | import { RouterTestingModule } from '@angular/router/testing'; 5 | import { MatButtonModule } from '@angular/material/button'; 6 | import { MatIconModule } from '@angular/material/icon'; 7 | import { MatListModule } from '@angular/material/list'; 8 | import { MatSidenavModule } from '@angular/material/sidenav'; 9 | import { MatToolbarModule } from '@angular/material/toolbar'; 10 | 11 | import { NavComponentComponent } from './nav-component.component'; 12 | 13 | describe('NavComponentComponent', () => { 14 | let component: NavComponentComponent; 15 | let fixture: ComponentFixture; 16 | 17 | beforeEach(waitForAsync(() => { 18 | TestBed.configureTestingModule({ 19 | imports: [ 20 | NoopAnimationsModule, 21 | LayoutModule, 22 | MatButtonModule, 23 | MatIconModule, 24 | MatListModule, 25 | MatSidenavModule, 26 | MatToolbarModule, 27 | RouterTestingModule, 28 | ] 29 | }).compileComponents(); 30 | })); 31 | 32 | beforeEach(() => { 33 | fixture = TestBed.createComponent(NavComponentComponent); 34 | component = fixture.componentInstance; 35 | fixture.detectChanges(); 36 | }); 37 | 38 | it('should compile', () => { 39 | expect(component).toBeTruthy(); 40 | }); 41 | }); 42 | -------------------------------------------------------------------------------- /src/app/nav-component/nav-component.component.ts: -------------------------------------------------------------------------------- 1 | import { Component } from '@angular/core'; 2 | 3 | import { BreakpointObserver, Breakpoints } from '@angular/cdk/layout'; 4 | import { MatIconModule } from '@angular/material/icon'; 5 | import { MatListModule } from '@angular/material/list'; 6 | import { MatSidenavModule } from '@angular/material/sidenav'; 7 | import { MatToolbarModule } from '@angular/material/toolbar'; 8 | 9 | import { Observable } from 'rxjs'; 10 | import { map, shareReplay } from 'rxjs/operators'; 11 | 12 | import { COMMON, ROUTER } from '@imports'; 13 | 14 | @Component({ 15 | selector: 'app-nav-component', 16 | standalone: true, 17 | templateUrl: './nav-component.component.html', 18 | imports: [COMMON, MatIconModule, MatListModule, MatSidenavModule, MatToolbarModule, ROUTER], 19 | styleUrls: ['./nav-component.component.scss'] 20 | }) 21 | export class NavComponentComponent { 22 | 23 | isHandset$: Observable = this.breakpointObserver.observe(Breakpoints.Handset) 24 | .pipe( 25 | map(result => result.matches), 26 | shareReplay() 27 | ); 28 | 29 | constructor(private breakpointObserver: BreakpointObserver) {} 30 | 31 | } 32 | -------------------------------------------------------------------------------- /src/app/services/busy.service.ts: -------------------------------------------------------------------------------- 1 | import { Injectable } from '@angular/core'; 2 | import { BehaviorSubject, Observable } from 'rxjs'; 3 | import { distinctUntilChanged, finalize, scan, shareReplay, take } from 'rxjs/operators'; 4 | 5 | export interface BusyState { 6 | /** True if is busy */ 7 | isBusy: boolean; 8 | /** Current busy service message */ 9 | message: string; 10 | /** Should delay before showing spinner & message */ 11 | delay: boolean; 12 | } 13 | 14 | export const notBusy: BusyState = { isBusy: false, message: '', delay: true }; 15 | 16 | @Injectable({ providedIn: 'root' }) 17 | export class BusyService { 18 | private busyCounter = 0; 19 | private busySubject = new BehaviorSubject(notBusy); 20 | 21 | busyState$ = this.busySubject.pipe( 22 | scan( 23 | (oldValue, value) => { 24 | return oldValue.isBusy === value.isBusy && 25 | oldValue.message === value.message && 26 | oldValue.delay === value.delay 27 | ? oldValue 28 | : { ...value }; 29 | }, 30 | { ...notBusy } as BusyState 31 | ), 32 | distinctUntilChanged(), 33 | shareReplay({ bufferSize: 1, refCount: true }) 34 | ); 35 | 36 | /** 37 | * Indicate busy until the source observable completes. 38 | * Display spinner (and message) after a delay if observable has not yet completed. 39 | * @param message The loading message to be displayed 40 | * @param source Observable that the busy service should watch 41 | * @return piped continuation of the source observable. Caller should subscribe to this. 42 | * Warning: busy and live forever if observable fails to terminate 43 | */ 44 | busy$(message: string, source: Observable): Observable { 45 | this.increment(message, false, true); 46 | return source.pipe(finalize(() => this.decrement())); 47 | } 48 | 49 | /** 50 | * Indicate busy until the observable completes, 51 | * Display spinner (and message) immediately 52 | * @param message The loading message to be displayed 53 | * @param source Observable that the busy service should watch 54 | * @return piped continuation of the source observable. Caller should subscribe to this. 55 | * Warning: busy and live forever if observable fails to terminate 56 | */ 57 | busyNoDelay$(message: string, source: Observable): Observable { 58 | this.increment(message, true, false); 59 | return source.pipe(finalize(() => this.decrement())); 60 | } 61 | 62 | /** 63 | * Increment the count of busy processes and set current message if no message pending. 64 | * Causes isBusy$ to emit true. 65 | * @param message The new current message 66 | * @param overrideMessage True if should override current message (default: false) 67 | * @param delay True if should delay displaying the spinner and message (default: true) 68 | */ 69 | increment(msg?: string, overrideMessage = false, delay = true): void { 70 | this.busyCounter++; 71 | let oldState: BusyState; 72 | this.busyState$.pipe(take(1)).subscribe((state) => (oldState = state)); 73 | 74 | // change message with caller's if provided and either there is no current message or should override it 75 | const message = msg && (!oldState!.message || overrideMessage) ? msg : oldState!.message; 76 | this.busySubject.next({ isBusy: true, message, delay }); 77 | } 78 | 79 | /** 80 | * Decrement the count of busy processes. 81 | * If no more busy processes, clear the current message and indicate no longer busy 82 | * (isBusy$ emits false). 83 | * @param message The new current message 84 | */ 85 | decrement(): void { 86 | if (this.busyCounter > 0) { 87 | this.busyCounter--; 88 | } 89 | if (this.busyCounter === 0) { 90 | this.busySubject.next(notBusy); 91 | } 92 | } 93 | } 94 | -------------------------------------------------------------------------------- /src/app/services/company-form-validation-demo.service.ts: -------------------------------------------------------------------------------- 1 | import { Injectable, Inject } from '@angular/core'; 2 | import { AbstractControl, NgForm } from '@angular/forms'; 3 | 4 | import { AppValidationContext } from '@validators/app-validation-context'; 5 | import { Company } from '@model'; 6 | import { companySyncValidationSuite, companyAsyncValidationSuite } from '@validators'; 7 | import { Indexable } from '@utils'; 8 | import { VALIDATION_CONTEXT } from '@validation/validation-context'; 9 | 10 | @Injectable({ providedIn: 'root' }) 11 | export class CompanyFormValidationDemoService { 12 | 13 | constructor(@Inject(VALIDATION_CONTEXT) private appValidationContext: AppValidationContext) { 14 | } 15 | 16 | demoReactive(ngForm: NgForm) { 17 | console.groupCollapsed('Company Form State'); 18 | console.log('ngForm.controls', ngForm.controls); 19 | const data = ngForm.value; 20 | console.log('Company form data value', data); 21 | const companyVm: Partial = { ...data.general, ...data.workAddress } 22 | this.demoVest(companyVm); 23 | } 24 | 25 | demoTD(controls: Indexable, companyVm: Partial) { 26 | console.groupCollapsed('Company Form State'); 27 | console.log('ngForm.controls', controls); 28 | console.log('Company Vm', companyVm); 29 | this.demoVest(companyVm); 30 | } 31 | 32 | /** DEMO: validate the company form data and display aspects of it in the browser console */ 33 | demoVest(companyVm: Partial) { 34 | companySyncValidationSuite.reset(); 35 | const syncResult = companySyncValidationSuite(companyVm, undefined, undefined, this.appValidationContext); 36 | const syncErrors = syncResult.getErrors(); 37 | console.log('company form vest synchronous validation state', syncResult); 38 | console.log('vest synchronous validation errors', syncErrors); 39 | 40 | companyAsyncValidationSuite.reset(); 41 | companyAsyncValidationSuite(companyVm, undefined, undefined, this.appValidationContext) 42 | .done(asyncResult => { 43 | console.log('company form vest asynchronous validation state', asyncResult); 44 | const asyncErrors = asyncResult.getErrors() 45 | console.log('vest asynchronous validation errors', asyncErrors); 46 | console.groupEnd(); 47 | const errorCount = Object.keys(syncErrors).length + Object.keys(asyncErrors).length; 48 | alert(`Has ${errorCount ? errorCount : 'no'} errors. Look at browser console.`); 49 | }); 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /src/app/services/data.service.ts: -------------------------------------------------------------------------------- 1 | import { Injectable } from '@angular/core'; 2 | import { BehaviorSubject, Observable, of, Subject } from 'rxjs'; 3 | import { catchError, concatMap, distinctUntilChanged, first, map } from 'rxjs/operators'; 4 | 5 | import { BusyService } from './busy.service'; 6 | import { Cache, Company, Employee, EmployeeTax } from '@model'; 7 | import { RemoteDataService } from './remote-data.service'; 8 | 9 | /** Data graph for a single Company */ 10 | export interface CompanyData { 11 | company: Company | undefined; 12 | employees: Employee[]; 13 | employeeTaxes: EmployeeTax[]; 14 | } 15 | 16 | /** List of companies (for display in console) */ 17 | export interface CompanyListItem { 18 | id: string; 19 | name: string; 20 | } 21 | 22 | const currentCompanyIdKey = '_currentCompanyId'; 23 | 24 | /** Data access facade over ngrx-like observable store. */ 25 | @Injectable({ providedIn: 'root' }) 26 | export class DataService { 27 | 28 | private cacheSubject = new BehaviorSubject(new Cache()); 29 | /** Observable of the application cache. Remember to unsubscribe. */ 30 | cache$ = this.cacheSubject.asObservable(); 31 | 32 | /** Observable of the current company's data graph. Remember to unsubscribe. */ 33 | companyData$: Observable = this.cache$.pipe( 34 | map(({company, employees, employeeTaxes}) => ({company, employees, employeeTaxes}))); 35 | 36 | /** Observable of the current company record. Remember to unsubscribe. */ 37 | company$: Observable = this.companyData$.pipe( 38 | map(({ company }) => company), 39 | distinctUntilChanged() 40 | ); 41 | 42 | /** Observable of the current company's employees. Remember to unsubscribe. */ 43 | employees$: Observable = this.companyData$.pipe( 44 | map(({ employees }) => employees), 45 | distinctUntilChanged() 46 | ); 47 | 48 | /** Observable of the current company's employee taxes. Remember to unsubscribe. */ 49 | employeeTaxes$: Observable = this.companyData$.pipe( 50 | map(({ employeeTaxes }) => employeeTaxes), 51 | distinctUntilChanged() 52 | ); 53 | 54 | private errorSubject = new Subject; 55 | /** Observable of data service errors as they happen. 56 | * Remember to unsubscribe. 57 | */ 58 | errors$ = this.errorSubject.asObservable(); 59 | 60 | constructor( 61 | private busyService: BusyService, 62 | private remoteDataService: RemoteDataService 63 | ) { } 64 | 65 | /** Return cached data at the moment of this method's execution. */ 66 | cacheNow(): Cache { 67 | // This technique relies on synchronous nature of cache$. 68 | let cache: Cache; 69 | this.cache$.pipe(first()).subscribe(c => cache = c); 70 | return cache!; 71 | } 72 | 73 | /** Clear the company data graph currently in cache. */ 74 | clearCachedCompany() { 75 | const cache = { 76 | ...this.cacheNow(), 77 | company: undefined, 78 | employees: [], 79 | employeeTaxes: [], 80 | currentCompanyId: '', 81 | loading: false, 82 | } 83 | window.localStorage.setItem(currentCompanyIdKey, ''); 84 | this.cacheSubject.next(cache); 85 | return false; 86 | } 87 | 88 | /** Create a new company and load it. 89 | * @param [name] optional name of the created company 90 | * @returns Terminating observable of the created CompanyData 91 | */ 92 | createCompany(name?: string): Observable { 93 | return this.remoteDataService.createCompany(name); 94 | } 95 | 96 | /** Dump the app cache to the console for inspection. */ 97 | dumpCache() { 98 | const cache = this.cacheNow(); 99 | console.log('App Cache', cache); 100 | } 101 | 102 | /** Return terminating observable of list of companies in the mock db */ 103 | getCompanyList(): Observable{ 104 | return this.busyService.busyNoDelay$('Loading company list ...', this.remoteDataService.getCompanyList()); 105 | } 106 | 107 | /** Initialize the current company in cache when the app loads. */ 108 | init(): void { 109 | let loader$: Observable; 110 | let id = window.localStorage.getItem(currentCompanyIdKey); 111 | if (id == null) { 112 | // Demo start: never loaded a company before; load the first company. 113 | loader$ = this.remoteDataService.getCompanyList().pipe( 114 | concatMap(list => { 115 | id = list && list[0].id; 116 | return id ? this.loadCompanyById(id) : of(this.clearCachedCompany()); 117 | }) 118 | ); 119 | } else { 120 | loader$ = this.loadCompanyById(id); 121 | } 122 | loader$.subscribe( 123 | _ => this.dumpCache() // diagnostic 124 | ); 125 | } 126 | 127 | /** Load the cache with the company data graph for the company with the given id. 128 | * @returns Terminating observable that emits true if found and loaded or false if failed. 129 | */ 130 | loadCompanyById(id: string): Observable { 131 | const loader$ = this.remoteDataService.getCompanyDataById(id).pipe( 132 | catchError((msg: string) => { 133 | this.errorSubject.next(msg); 134 | console.error(msg); 135 | return of(null); 136 | }), 137 | map(companyData => this.loadCompanyDataToCache(companyData)) 138 | ); 139 | return this.busyService.busyNoDelay$('Loading company data ...', loader$); 140 | } 141 | 142 | private loadCompanyDataToCache(companyData: CompanyData| null | undefined): boolean { 143 | const currentCompanyId = companyData?.company?.id; 144 | if (currentCompanyId) { 145 | const cache = { 146 | ...this.cacheNow(), 147 | ...companyData, 148 | currentCompanyId, 149 | loading: false, 150 | } 151 | window.localStorage.setItem(currentCompanyIdKey, currentCompanyId); 152 | this.cacheSubject.next(cache); 153 | return true 154 | } else { 155 | this.clearCachedCompany(); // No company data => clear company data in cache. 156 | return false; 157 | } 158 | } 159 | 160 | /** Reload current company based on the currentCompanyId in local storage. 161 | * If the current company was already loaded, will reload from remote, 162 | * assuming that the currentCompanyId in local storage is the same as id of the loaded company 163 | * (as should be the case). 164 | */ 165 | reloadCurrentCompany(): Observable { 166 | const id = window.localStorage.getItem(currentCompanyIdKey); 167 | return id ? this.loadCompanyById(id) : of(this.clearCachedCompany()); 168 | } 169 | 170 | /** Reset the remote mock database to its initial state. */ 171 | resetDb() { 172 | this.remoteDataService.resetDb(); 173 | } 174 | 175 | /** Save company data after updating the cache 176 | * @param companyData with one, some, or all of the CompanyData properties (company graph). 177 | * Critical: each data property must be a complete replacement for that property. 178 | * @returns Terminating boolean observable emitting true (if succeeded) else false 179 | */ 180 | saveCompanyData(companyData: Partial): Observable { 181 | try { 182 | const { company, employees, employeeTaxes} = companyData; 183 | // TODO: add safety checks 184 | const currentCache = this.cacheNow(); 185 | const saveData: CompanyData = { 186 | company: company ?? currentCache.company, 187 | employees: employees ?? currentCache.employees, 188 | employeeTaxes: employeeTaxes ?? currentCache.employeeTaxes, 189 | } 190 | 191 | // Update cache optimistically 192 | const newCache = { ...currentCache, ...saveData }; 193 | this.cacheSubject.next(newCache); 194 | const saver$ = this.remoteDataService.saveCompanyData(saveData); 195 | return this.busyService.busy$('Saving company data ...', saver$); 196 | } catch(e) { 197 | console.error('Company save failed', e); 198 | return of(false); 199 | } 200 | } 201 | } 202 | -------------------------------------------------------------------------------- /src/app/services/db.ts: -------------------------------------------------------------------------------- 1 | import { Company, Employee, EmployeeTax } from '@model'; 2 | 3 | /** Mock database */ 4 | export class Db { 5 | Company: Company[] = []; 6 | Employee: Employee[] = []; 7 | EmployeeTax: EmployeeTax[] = []; 8 | } 9 | -------------------------------------------------------------------------------- /src/app/services/demo-data.ts: -------------------------------------------------------------------------------- 1 | import { Company, Employee, EmployeeTax, EmployeeStatus, EmployeeType, FilingStatus, TaxType } from '@model'; 2 | import { Db } from './db'; 3 | 4 | interface Example { 5 | company: Company; 6 | employees: Employee[]; 7 | employeeTaxes: EmployeeTax[]; 8 | } 9 | 10 | /** return a newly created data for the demo */ 11 | export function createDemoData() { 12 | 13 | const db = new Db(); 14 | 15 | addExample(createMarvelous()); 16 | return db; 17 | 18 | /// helpers 19 | 20 | function addExample({ company, employees, employeeTaxes }: Example) { 21 | db.Company.push(company); 22 | db.Employee.push(...employees); 23 | db.EmployeeTax.push(...employeeTaxes); 24 | } 25 | 26 | function createMarvelous(): Example { 27 | 28 | const companyId = '14869218ca0645cea77d491325216e46'; 29 | 30 | const company: Company = { 31 | id: companyId, 32 | fein: '13-1234567', 33 | legalName: 'Marvelous Products', 34 | workAddress: { 35 | street: '321 E Chapman Ave', 36 | street2: null, 37 | city: 'Fullerton', 38 | state: 'CA', 39 | postalCode: '92832', 40 | verified: true 41 | } 42 | } 43 | 44 | const adamId = 'a241473f45e547dab3a90162c1b903d0'; 45 | const bobId = 'b7c591310b5040a688360162c1b903d0'; 46 | const cathyId = 'cbf51450a77942a197f80170e1eabb23'; 47 | 48 | const employees: Employee[] = [ 49 | { 50 | id: adamId, 51 | companyId, 52 | 53 | street: 'Turnbull Canyon Rd', 54 | street2: 'Apt 301', 55 | city: 'Whittier', 56 | state: 'CA', 57 | postalCode: '90601', 58 | verified: true, 59 | 60 | birthDate: '1984-10-18T17:00:00Z', 61 | email: 'aa@marvelous.com', 62 | employeeStatus: EmployeeStatus.Active, 63 | employeeType: EmployeeType.FullTime, 64 | hireDate: '2005-04-01T17:00:00Z', 65 | name: 'Adam Adamson' 66 | }, 67 | { 68 | id: bobId, 69 | companyId, 70 | 71 | street: '1951 N Jones Blvd', 72 | street2: '', 73 | city: 'Las Vegas', 74 | state: 'NV', 75 | postalCode: '89108', 76 | verified: true, 77 | 78 | birthDate: '1984-10-18T17:00:00Z', 79 | email: 'bk@marvelous.com', 80 | employeeStatus: EmployeeStatus.Active, 81 | employeeType: EmployeeType.FullTime, 82 | hireDate: '2005-04-01T17:00:00Z', 83 | name: 'Bob Kazoo' 84 | }, 85 | { 86 | id: cathyId, 87 | companyId, 88 | 89 | street: '2099 N 63rd St', 90 | street2: '', 91 | city: 'Philadelphia', 92 | state: 'PA', 93 | postalCode: '19151', 94 | verified: true, 95 | 96 | birthDate: '1984-10-18T17:00:00Z', 97 | email: 'cs@marvelous.com', 98 | employeeStatus: EmployeeStatus.Active, 99 | employeeType: EmployeeType.FullTime, 100 | hireDate: '2005-04-01T17:00:00Z', 101 | name: 'Cathy Sing' 102 | }, 103 | ]; 104 | 105 | const employeeTaxes: EmployeeTax[] = [ 106 | // Adam 107 | { 108 | id: '3818e5c1eb2649f3a4b40166a12ec8ec', 109 | companyId, 110 | employeeId: adamId, 111 | isExempt: false, 112 | withholdingAllowance: 0, 113 | extraWithholding: 0, 114 | name: 'SOC SEC EMPLOYEE', 115 | state: null, 116 | taxCode: 'FE0000-003', 117 | taxType: TaxType.Federal, 118 | }, 119 | { 120 | id: '14cd941e1b73414098ad0166a12ec8ec', 121 | companyId, 122 | employeeId: adamId, 123 | isExempt: false, 124 | withholdingAllowance: 0, 125 | extraWithholding: 0, 126 | name: 'MED EMPLOYEE', 127 | state: null, 128 | taxCode: 'FE0000-005', 129 | taxType: TaxType.Federal, 130 | }, 131 | { 132 | id: '1987665c80a3400983310166a12ec8ec', 133 | companyId, 134 | employeeId: adamId, 135 | isExempt: false, 136 | withholdingAllowance: 3, 137 | extraWithholding: 0, 138 | name: 'FEDERAL WITHHOLDING', 139 | 'filingStatus': FilingStatus.Married, 140 | state: null, 141 | taxCode: 'FE0000-001', 142 | taxType: TaxType.Federal, 143 | }, 144 | { 145 | id: '2a9cbb15234f43bc89070166a12ec8ec', 146 | companyId, 147 | employeeId: adamId, 148 | isExempt: false, 149 | withholdingAllowance: 0, 150 | extraWithholding: 0, 151 | name: 'SOC SEC EMPLOYER', 152 | state: null, 153 | taxCode: 'FE0000-004', 154 | taxType: TaxType.Federal, 155 | }, 156 | { 157 | id: 'fe703615ddd34d659ddb0166a12ec8ec', 158 | companyId, 159 | employeeId: adamId, 160 | isExempt: false, 161 | withholdingAllowance: 0, 162 | extraWithholding: 0, 163 | name: 'MED EMPLOYER', 164 | state: null, 165 | taxCode: 'FE0000-006', 166 | taxType: TaxType.Federal, 167 | }, 168 | { 169 | id: '211a5786c39249caa4b70166a12ec8ec', 170 | companyId, 171 | employeeId: adamId, 172 | isExempt: false, 173 | withholdingAllowance: 0, 174 | extraWithholding: 0, 175 | name: 'FEDERAL UNEMPLOYMENT EMPLOYER', 176 | state: null, 177 | taxCode: 'FE0000-010', 178 | taxType: TaxType.Federal, 179 | }, 180 | { 181 | id: '878d645f03444b6b96950166a12ec8ec', 182 | companyId, 183 | employeeId: adamId, 184 | isExempt: false, 185 | withholdingAllowance: 4, 186 | extraWithholding: 0, 187 | name: 'NEW YORK WITHHOLDING', 188 | taxCode: 'NY0000-001', 189 | state: 'NY', 190 | taxType: TaxType.State, 191 | 'filingStatus': FilingStatus.Single 192 | }, 193 | { 194 | id: 'c56354edd3e04233adbe0166a12ec8ec', 195 | companyId, 196 | employeeId: adamId, 197 | isExempt: false, 198 | withholdingAllowance: 0, 199 | extraWithholding: 0, 200 | name: 'NEW YORK STATE UNEMPLOYMENT EMPLOYER', 201 | state: 'NY', 202 | taxCode: 'NY0000-010', 203 | taxType: TaxType.State 204 | }, 205 | { 206 | id: '5b791c4fe8ca4e11bd550166a12ec8ec', 207 | companyId, 208 | employeeId: adamId, 209 | isExempt: false, 210 | withholdingAllowance: 0, 211 | extraWithholding: 0, 212 | name: 'NEW YORK REEMPLOYMENT SERVICE EMPLOYER', 213 | state: 'NY', 214 | taxCode: 'NY0000-128', 215 | taxType: TaxType.State 216 | }, 217 | { 218 | id: 'a88dc1a8789c4fdfa07d0166a12ec8ec', 219 | companyId, 220 | employeeId: adamId, 221 | isExempt: false, 222 | withholdingAllowance: 0, 223 | extraWithholding: 0, 224 | name: 'NEW YORK MCTMT EMPLOYER', 225 | state: 'NY', 226 | taxCode: 'NY0000-145', 227 | taxType: TaxType.County 228 | }, 229 | { 230 | id: '8f1f9a238fe6445da9df0166a12ec8ec', 231 | companyId, 232 | employeeId: adamId, 233 | isExempt: false, 234 | withholdingAllowance: 0, 235 | extraWithholding: 0, 236 | name: 'NEW YORK', 237 | state: 'NY', 238 | taxCode: 'NY0061-001', 239 | taxType: TaxType.City 240 | }, 241 | 242 | // Bob 243 | { 244 | id: 'e3f384ff4785415094f80170b6c49965', 245 | companyId, 246 | employeeId: bobId, 247 | isExempt: false, 248 | withholdingAllowance: 0, 249 | extraWithholding: 0, 250 | name: 'SOC SEC EMPLOYEE', 251 | state: null, 252 | taxCode: 'FE0000-003', 253 | taxType: TaxType.Federal, 254 | }, 255 | { 256 | id: 'ad6bf542f6fb438aa0ae0170b6c49965', 257 | companyId, 258 | employeeId: bobId, 259 | isExempt: false, 260 | withholdingAllowance: 0, 261 | extraWithholding: 0, 262 | name: 'MED EMPLOYEE', 263 | state: null, 264 | taxCode: 'FE0000-005', 265 | taxType: TaxType.Federal, 266 | }, 267 | { 268 | id: '468d2eb45eb94b1eb0220170b6c49965', 269 | companyId, 270 | employeeId: bobId, 271 | isExempt: false, 272 | withholdingAllowance: 0, 273 | extraWithholding: 0, 274 | name: 'FEDERAL WITHHOLDING', 275 | state: null, 276 | taxCode: 'FE0000-001', 277 | taxType: TaxType.Federal, 278 | 'filingStatus': FilingStatus.HeadOfHousehold, 279 | }, 280 | { 281 | id: 'bf231870c7cb4908a08b0170b6c49965', 282 | companyId, 283 | employeeId: bobId, 284 | isExempt: false, 285 | withholdingAllowance: 0, 286 | extraWithholding: 0, 287 | name: 'SOC SEC EMPLOYER', 288 | state: null, 289 | taxCode: 'FE0000-004', 290 | taxType: TaxType.Federal, 291 | }, 292 | { 293 | id: '8e9e1b6346bb49e093cd0170b6c49965', 294 | companyId, 295 | employeeId: bobId, 296 | isExempt: false, 297 | withholdingAllowance: 0, 298 | extraWithholding: 0, 299 | name: 'MED EMPLOYER', 300 | state: null, 301 | taxCode: 'FE0000-006', 302 | taxType: TaxType.Federal, 303 | }, 304 | { 305 | id: '82cdc489159741c2a05e0170b6c49965', 306 | companyId, 307 | employeeId: bobId, 308 | isExempt: false, 309 | withholdingAllowance: 0, 310 | extraWithholding: 0, 311 | name: 'FEDERAL UNEMPLOYMENT EMPLOYER', 312 | state: null, 313 | taxCode: 'FE0000-010', 314 | taxType: TaxType.Federal, 315 | }, 316 | { 317 | id: '28ae3396535846f1833b0170b6c49965', 318 | companyId, 319 | employeeId: bobId, 320 | isExempt: false, 321 | withholdingAllowance: 0, 322 | extraWithholding: 0, 323 | name: 'NEVADA STATE UNEMPLOYMENT EMPLOYER', 324 | state: 'NV', 325 | taxCode: 'NV0000-010', 326 | taxType: TaxType.State 327 | }, 328 | { 329 | id: 'caeeae7f19c74e02b4d30170b6c49965', 330 | companyId, 331 | employeeId: bobId, 332 | isExempt: false, 333 | withholdingAllowance: 0, 334 | extraWithholding: 0, 335 | name: 'NEVADA MODIFIED BUSINESS TAX EMPLOYER', 336 | state: 'NV', 337 | taxCode: 'NV0000-134', 338 | taxType: TaxType.State 339 | }, 340 | { 341 | id: '1ee41b95406a483c9e5e0170b6c49965', 342 | companyId, 343 | employeeId: bobId, 344 | isExempt: false, 345 | withholdingAllowance: 0, 346 | extraWithholding: 0, 347 | name: 'NEVADA CAREER ENHANCEMENT EMPLOYER', 348 | state: 'NV', 349 | taxCode: 'NV0000-131', 350 | taxType: TaxType.State 351 | }, 352 | 353 | // Cathy 354 | { 355 | id: 'c7ce674ec719417899ca0170e1ed1b78', 356 | companyId, 357 | employeeId: cathyId, 358 | isExempt: false, 359 | withholdingAllowance: 0, 360 | extraWithholding: 0, 361 | name: 'SOC SEC EMPLOYEE', 362 | state: null, 363 | taxCode: 'FE0000-003', 364 | taxType: TaxType.Federal, 365 | }, 366 | { 367 | id: '29e7b264b1e34bacba9e0170e1ed1b79', 368 | companyId, 369 | employeeId: cathyId, 370 | isExempt: false, 371 | withholdingAllowance: 0, 372 | extraWithholding: 0, 373 | name: 'MED EMPLOYEE', 374 | state: null, 375 | taxCode: 'FE0000-005', 376 | taxType: TaxType.Federal, 377 | }, 378 | { 379 | id: 'bbcdaaa9c9c94f88a73a0170e1ed1b79', 380 | companyId, 381 | employeeId: cathyId, 382 | isExempt: false, 383 | withholdingAllowance: 0, 384 | extraWithholding: 0, 385 | name: 'FEDERAL WITHHOLDING', 386 | state: null, 387 | taxCode: 'FE0000-001', 388 | taxType: TaxType.Federal, 389 | 'filingStatus': FilingStatus.Single, 390 | }, 391 | { 392 | id: 'ae705f6c6d7d4bdca8cc0170e1ed1b79', 393 | companyId, 394 | employeeId: cathyId, 395 | isExempt: false, 396 | withholdingAllowance: 0, 397 | extraWithholding: 0, 398 | name: 'SOC SEC EMPLOYER', 399 | state: null, 400 | taxCode: 'FE0000-004', 401 | taxType: TaxType.Federal, 402 | }, 403 | { 404 | id: 'eee4af76d2db415bb8e50170e1ed1b79', 405 | companyId, 406 | employeeId: cathyId, 407 | isExempt: false, 408 | withholdingAllowance: 0, 409 | extraWithholding: 0, 410 | name: 'MED EMPLOYER', 411 | state: null, 412 | taxCode: 'FE0000-006', 413 | taxType: TaxType.Federal, 414 | }, 415 | { 416 | id: '88f682be3c86487a8fc10170e1ed1b7a', 417 | companyId, 418 | employeeId: cathyId, 419 | isExempt: false, 420 | withholdingAllowance: 0, 421 | extraWithholding: 0, 422 | name: 'FEDERAL UNEMPLOYMENT EMPLOYER', 423 | state: null, 424 | taxCode: 'FE0000-010', 425 | taxType: TaxType.Federal, 426 | }, 427 | { 428 | id: '15cfbec1aed0435da9800170e1ed1b7a', 429 | companyId, 430 | employeeId: cathyId, 431 | isExempt: false, 432 | withholdingAllowance: 0, 433 | extraWithholding: 0, 434 | name: 'NEVADA STATE UNEMPLOYMENT EMPLOYER', 435 | state: 'NV', 436 | taxCode: 'NV0000-010', 437 | taxType: TaxType.State 438 | }, 439 | { 440 | id: '2c8e79f8263e49aca47f0170e1ed1b7a', 441 | companyId, 442 | employeeId: cathyId, 443 | isExempt: false, 444 | withholdingAllowance: 0, 445 | extraWithholding: 0, 446 | name: 'NEVADA MODIFIED BUSINESS TAX EMPLOYER', 447 | state: 'NV', 448 | taxCode: 'NV0000-134', 449 | taxType: TaxType.State 450 | }, 451 | { 452 | id: '2684da1af0394bce84d00170e1ed1b7a', 453 | companyId, 454 | employeeId: cathyId, 455 | isExempt: false, 456 | withholdingAllowance: 0, 457 | extraWithholding: 0, 458 | name: 'NEVADA CAREER ENHANCEMENT EMPLOYER', 459 | state: 'NV', 460 | taxCode: 'NV0000-131', 461 | taxType: TaxType.State 462 | } 463 | 464 | ]; 465 | 466 | return { company, employees, employeeTaxes } 467 | } 468 | 469 | } 470 | -------------------------------------------------------------------------------- /src/app/services/fein-validation.service.ts: -------------------------------------------------------------------------------- 1 | import { Injectable } from '@angular/core'; 2 | import { firstValueFrom } from 'rxjs'; 3 | 4 | import { FeinValidationResponse, RemoteFeinValidationService } from './remote-fein-validation.service'; 5 | export { FeinValidationResponse }; 6 | 7 | @Injectable({ providedIn: 'root' }) 8 | export class FeinValidationService { 9 | 10 | constructor(private remoteFeinValidationService: RemoteFeinValidationService) { } 11 | 12 | /** Cache of FEIN Validation Response promises accumulated in this user session. 13 | * These promises may take time to resolve. 14 | */ 15 | private responses: { [fein: string]: Promise } = {}; 16 | 17 | /** Check with the FEIN Validation Service if an FEIN/Legal Name combination is valid 18 | * @returns Promise of the service response. May be a cached response. 19 | */ 20 | check(fein: string): Promise { 21 | if (!isGoodFein(fein)) { 22 | return Promise.reject(`Bad FEIN "${fein}"`); 23 | } 24 | 25 | // Check the cached responses first. 26 | const cachedResponse = this.responses[fein]; 27 | if (cachedResponse) { 28 | return cachedResponse; 29 | } else { 30 | const promise = firstValueFrom(this.remoteFeinValidationService.check(fein)); 31 | this.responses[fein] = promise; // cache the promise of the response 32 | return promise; 33 | } 34 | } 35 | } 36 | 37 | /** Return true if the fein value is a well-formed FEIN number although it might not be a real FEIN. */ 38 | export function isGoodFein(fein?: string): boolean { 39 | return fein ? /^\d{2}-\d{7}$/.test(fein) : false; 40 | } 41 | -------------------------------------------------------------------------------- /src/app/services/index.ts: -------------------------------------------------------------------------------- 1 | export * from './busy.service'; 2 | export * from './data.service'; 3 | export * from './fein-validation.service'; 4 | export * from './page-leave-guard'; 5 | export * from './remote-data.service'; 6 | export * from './validation.service'; 7 | -------------------------------------------------------------------------------- /src/app/services/page-leave-guard.ts: -------------------------------------------------------------------------------- 1 | import { Injectable } from '@angular/core'; 2 | import { CanDeactivate } from '@angular/router'; 3 | import { Observable } from 'rxjs'; 4 | /** 5 | * Routing guard the asks a component if (when) the user can leave the page. 6 | * Implements the router's `CanDeactivate` by asking the component if it has 7 | * a `canLeave` method and calling that method if it does. 8 | * Because that method can be async, gives the component time to save or do something else 9 | * before leaving OR it can just cancel leaving. 10 | */ 11 | @Injectable({ providedIn: 'root' }) 12 | export class PageLeaveGuard implements CanDeactivate { 13 | 14 | canDeactivate( 15 | component: any, 16 | // currentRoute: ActivatedRouteSnapshot, 17 | // currentState: RouterStateSnapshot, 18 | // nextState?: RouterStateSnapshot 19 | ): Promise | Observable | boolean{ 20 | 21 | if (component?.canLeave) { 22 | const res: Promise | Observable | boolean = component.canLeave(); 23 | return res; 24 | } else { 25 | return true; // leave immediately because doesn't have `canLeave` 26 | } 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /src/app/services/remote-data.service.ts: -------------------------------------------------------------------------------- 1 | import { Injectable } from '@angular/core'; 2 | import { Observable, of, throwError } from 'rxjs'; 3 | import { delay, map } from 'rxjs/operators'; 4 | 5 | import { createDemoData } from './demo-data'; 6 | import { Company, createCompany } from '@model'; 7 | import { CompanyData, CompanyListItem } from './data.service'; 8 | import { Db } from './db'; 9 | import { deepClone } from '@utils'; 10 | 11 | const dbKey = '_db'; 12 | 13 | /** Delay response by this number of milliseconds to simulate latency. */ 14 | const latencyDelayMs = 1500; 15 | 16 | /** Simulate the behavior of a remote data service and API. */ 17 | @Injectable({ providedIn: 'root' }) 18 | export class RemoteDataService { 19 | 20 | private db = new Db(); 21 | 22 | init() { 23 | let db: Db | undefined; 24 | const dbString = window.localStorage.getItem(dbKey); 25 | if (dbString) { 26 | try { 27 | db = JSON.parse(dbString); 28 | console.log('Loaded mock database from local storage'); 29 | } catch (err) { 30 | console.error('Db in local storage is unreadable', err); 31 | } 32 | } 33 | this.db = db == null ? this.resetDb() : db; 34 | } 35 | 36 | createCompany(name?: string): Observable { 37 | const data: CompanyData = { 38 | company: createCompany(name), 39 | employees: [], 40 | employeeTaxes: [], 41 | } 42 | return of(this.saveCompanyDataCore(data)).pipe(delay(latencyDelayMs)); 43 | } 44 | 45 | /** Return terminating observable of list of companies in the mock db */ 46 | getCompanyList(): Observable { 47 | return of(this.db.Company).pipe( 48 | // Simulate time to load company list 49 | delay(latencyDelayMs), 50 | map(companies => { 51 | return companies.map(c => ({ id: c.id, name: c.legalName || '' })) 52 | }) 53 | ) 54 | } 55 | 56 | /** Get the company data graph for the company with the given id. */ 57 | getCompanyDataById(id: string): Observable { 58 | const company = this.db.Company.find(c => c.id === id); 59 | if (company) { 60 | return this.getCompanyData(company); 61 | } else { 62 | const msg = `Company with id: ${id} not found.`; 63 | console.error(msg); 64 | // Simulate time to look for (and not find) the company by this id 65 | return throwError(() => msg).pipe(delay(latencyDelayMs)); 66 | } 67 | } 68 | 69 | private getCompanyData(company: Company): Observable { 70 | const id = company.id; 71 | const data: CompanyData = { 72 | company: deepClone(company), 73 | employees: this.db.Employee.filter(e => e.companyId === id).map(e => deepClone(e)), 74 | employeeTaxes: this.db.EmployeeTax.filter(et => et.companyId === id).map(et => deepClone(et)), 75 | } 76 | // Simulate time to load company 77 | return of(data).pipe(delay(latencyDelayMs)); 78 | } 79 | 80 | /** Reset the remote mock database to its initial conditions. */ 81 | resetDb() { 82 | console.log('(Re)created the mock database'); 83 | this.db = createDemoData() ?? new Db(); 84 | this.storeDb(); 85 | return this.db; 86 | } 87 | 88 | saveCompanyData(companyData: CompanyData): Observable { 89 | try { 90 | this.saveCompanyDataCore(companyData); 91 | return of(true).pipe(delay(latencyDelayMs)); 92 | } catch (e) { 93 | console.error('RemoteDataService: Save CompanyData failed: ' + e); 94 | return throwError(() => 'Save CompanyData failed: ' + e); 95 | } 96 | } 97 | 98 | private saveCompanyDataCore(companyData: CompanyData): CompanyData { 99 | this.guardBadCompanyData(companyData); 100 | 101 | companyData = deepClone(companyData); 102 | const { company, employees, employeeTaxes } = companyData 103 | const companyId = company!.id; 104 | if (this.db.Company.some(c => c.id === companyId)) { 105 | // update existing company 106 | this.db.Company = this.db.Company.map(c => c.id === companyId ? company! : c); 107 | this.db.Employee = this.db.Employee.filter(ee => ee.companyId !== companyId).concat(employees); 108 | this.db.EmployeeTax = this.db.EmployeeTax.filter(et => et.companyId !== companyId).concat(employeeTaxes); 109 | } else { 110 | // add new company 111 | this.db.Company = this.db.Company.concat(company!); 112 | this.db.Employee = this.db.Employee.concat(employees); 113 | this.db.EmployeeTax = this.db.EmployeeTax.concat(employeeTaxes); 114 | } 115 | this.storeDb(); 116 | return companyData; 117 | } 118 | 119 | /** Throw if the supplied data are structurally bad. */ 120 | private guardBadCompanyData(companyData: CompanyData) { 121 | const { company, employees, employeeTaxes } = companyData; 122 | const companyId = company!.id; 123 | if (!companyId) { 124 | throw 'No company id'; 125 | } 126 | if (!company!.legalName) { 127 | throw 'No company legalName'; 128 | } 129 | if (employees.some(e => e.companyId !== companyId)) { 130 | throw 'An employee does not have the right companyId'; 131 | } 132 | if (employees.some(e => !e.id || 1 !== employees.filter(e2 => e2.id === e.id).length)) { 133 | throw 'There are blank or duplicate employee ids'; 134 | } 135 | if (employeeTaxes.some(et => et.companyId !== companyId)) { 136 | throw 'An employee tax does not have the right companyId'; 137 | } 138 | if (employeeTaxes.some(et => !et.id || 1 !== employeeTaxes.filter(et2 => et2.id === et.id).length)) { 139 | throw 'There are blank or duplicate employeeTax ids'; 140 | } 141 | } 142 | 143 | private storeDb() { 144 | window.localStorage.setItem(dbKey, JSON.stringify(this.db)); 145 | } 146 | } 147 | -------------------------------------------------------------------------------- /src/app/services/remote-fein-validation.service.ts: -------------------------------------------------------------------------------- 1 | import { Injectable } from '@angular/core'; 2 | import { Observable, of } from 'rxjs'; 3 | import { delay } from 'rxjs/operators'; 4 | 5 | import { Indexable } from '@core'; 6 | 7 | export interface FeinValidationResponse { 8 | fein: string; 9 | feinName?: string; 10 | } 11 | 12 | /** Delay response by this number of milliseconds to simulate latency. */ 13 | const latencyDelayMs = 2000; 14 | 15 | const knownFeins: Indexable = { 16 | '13-1234567': 'MARVELOUS PRODUCTS, INC.' 17 | } 18 | 19 | /** Mock the remote FEIN Validation Service */ 20 | @Injectable({ providedIn: 'root' }) 21 | export class RemoteFeinValidationService { 22 | /** Check if provided fein is registered with the IRS. 23 | * If the FEIN exists, return the FEIN and FEIN name. 24 | * If it doesn't, return the FEIN. 25 | * Special cases: 26 | * FEIN starting '22' is always valid and the FEIN name is the wildcard, '*'. 27 | * FEIN starting 66' is always invalid. 28 | */ 29 | check(fein: string): Observable { 30 | const response: FeinValidationResponse = { fein }; 31 | const lead = fein.substring(0, 2); // mock response based on lead 2 digits. 32 | if (lead === '22') { 33 | response.feinName = '*'; // Always OK 34 | } else if (lead === '66') { 35 | // Always BAD 36 | } else { 37 | response.feinName = knownFeins[fein]; 38 | } 39 | return of(response).pipe(delay(latencyDelayMs)); 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /src/app/services/validation.service.ts: -------------------------------------------------------------------------------- 1 | import { Injectable, Inject } from '@angular/core'; 2 | 3 | import { AppValidationContext } from '@validators/app-validation-context'; 4 | import { VALIDATION_CONTEXT } from '@validation/validation-context'; 5 | 6 | @Injectable({ providedIn: 'root' }) 7 | export class ValidationService { 8 | 9 | constructor(@Inject(VALIDATION_CONTEXT) private appValidationContext: AppValidationContext) { 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /src/app/settings-component/settings.component.ts: -------------------------------------------------------------------------------- 1 | import { Component, OnInit } from '@angular/core'; 2 | import { MatListModule } from '@angular/material/list'; 3 | 4 | import { concatMap, tap } from 'rxjs/operators'; 5 | 6 | import { Company } from '@model'; 7 | import { CompanyListItem, DataService } from '@services'; 8 | import { FORMS } from '@imports'; 9 | 10 | @Component({ 11 | selector: 'app-settings', 12 | standalone: true, 13 | template: ` 14 | 15 | 16 | 17 | Settings 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 |
29 | 30 |

Companies

31 |
32 | Current Company: {{ currentCompany ? currentCompany.legalName : 'none'}} 33 |
34 |

Company List:

35 | 36 | 37 | 38 | 39 |
40 |
41 | `, 42 | imports: [FORMS, MatListModule] 43 | }) 44 | export class SettingsComponent implements OnInit { 45 | companyList: CompanyListItem[] = []; 46 | currentCompany?: Company; 47 | 48 | constructor( 49 | private dataService: DataService, 50 | ) { } 51 | 52 | ngOnInit(): void { 53 | this.getCurrentCompany(); 54 | this.getCompanyList().subscribe(); 55 | } 56 | 57 | createCompany() { 58 | // New company number will be highest existing "New Company" number plus 1 59 | const coNum = this.companyList.reduce((acc, c) => { 60 | const match = c.name.match(/^New Company (\d*)$/); 61 | return match ? Math.max(1 + +match[1], acc) : acc; 62 | }, 1); 63 | this.dataService.createCompany('New Company ' + coNum).subscribe(({ company: newCo }) => { 64 | const id = newCo!.id; 65 | this.companyList.push({id, name: newCo!.legalName!}) 66 | this.load(id); 67 | }); 68 | } 69 | 70 | getCompanyList() { 71 | return this.dataService.getCompanyList().pipe( 72 | tap(list => this.companyList = list ) 73 | ) 74 | } 75 | 76 | getCurrentCompany() { 77 | const cache = this.dataService.cacheNow(); 78 | return this.currentCompany = cache.company; 79 | } 80 | 81 | dumpCache() { 82 | this.dataService.dumpCache(); 83 | } 84 | 85 | load(id: string) { 86 | this.dataService.loadCompanyById(id).subscribe(_ => { 87 | this.getCurrentCompany(); 88 | }); 89 | } 90 | 91 | reset() { 92 | const cache = this.dataService.cacheNow(); 93 | const currentId = cache.currentCompanyId; 94 | this.dataService.resetDb(); 95 | this.getCompanyList().pipe( 96 | concatMap(list => { 97 | const id = list.some(c => c.id === currentId) ? currentId : list[0].id; 98 | return this.dataService.loadCompanyById(id) 99 | }) 100 | ).subscribe(_ => { 101 | this.getCurrentCompany(); 102 | }); 103 | } 104 | } 105 | -------------------------------------------------------------------------------- /src/app/teaching-forms/about/about-lazy.component.ts: -------------------------------------------------------------------------------- 1 | import { Component } from "@angular/core"; 2 | 3 | import { COMMON } from "@imports"; 4 | 5 | @Component({ 6 | selector: 'app-about-lazy', 7 | standalone: true, 8 | imports: [COMMON], 9 | 10 | template: `

{{ title }}

` 11 | }) 12 | export class AboutLazyComponent { 13 | title = 'Standalone Demo'; 14 | visible = true; 15 | } 16 | -------------------------------------------------------------------------------- /src/app/teaching-forms/about/about.component.ts: -------------------------------------------------------------------------------- 1 | import { Component, OnInit, ViewChild, ViewContainerRef } from "@angular/core"; 2 | 3 | @Component({ 4 | selector: 'app-about', 5 | standalone: true, 6 | 7 | template: ` 8 |

About

9 | 10 | ` 11 | }) 12 | export class AboutComponent implements OnInit { 13 | title = 'Standalone Demo'; 14 | 15 | @ViewChild('container', {read: ViewContainerRef}) 16 | viewContainer!: ViewContainerRef; 17 | 18 | async ngOnInit() { 19 | const esm = await import('./about-lazy.component'); 20 | const ref = this.viewContainer.createComponent(esm.AboutLazyComponent) 21 | ref.instance.title = `Lazy About Sub Component !!`; 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src/app/teaching-forms/address-form-no-widget/address-form-no-widget.component.html: -------------------------------------------------------------------------------- 1 |
2 |
3 | 4 | 5 | 6 | {{ street.errors['error'] }} 7 | 8 | 9 | 10 | 11 | 12 | 13 |
14 | 15 |
16 | 17 | 18 | 19 | {{ city.errors['error'] }} 20 | 21 | 22 | 23 | 24 | 25 | 26 | {{ state.name }} 27 | 28 | 29 | 30 | {{ state.errors['error'] }} 31 | 32 | 33 |
34 | 35 |
36 | 37 | 38 | 39 | {{ postalCode.errors['error'] }} 40 | 41 | 42 |
43 |
44 | -------------------------------------------------------------------------------- /src/app/teaching-forms/address-form-no-widget/address-form-no-widget.component.ts: -------------------------------------------------------------------------------- 1 | import { Component, Input } from '@angular/core'; 2 | 3 | import { Address } from '@model'; 4 | import { formContainerViewProvider } from '@core'; 5 | import { FORMS } from '@imports'; 6 | import { UsStates } from '@model'; 7 | 8 | @Component({ 9 | selector: 'app-address-form', 10 | standalone: true, 11 | templateUrl: './address-form-no-widget.component.html', 12 | viewProviders: [formContainerViewProvider], 13 | imports: [FORMS], 14 | }) 15 | export class AddressFormComponent { 16 | @Input() vm?: Address 17 | 18 | /** Name for the formGroup when added to the parent form. Defaults to 'address'. */ 19 | // eslint-disable-next-line @angular-eslint/no-input-rename 20 | @Input('name') ngModelGroupName = 'address'; 21 | 22 | states = UsStates; 23 | } 24 | -------------------------------------------------------------------------------- /src/app/teaching-forms/address-ngmodule-form/address-ngmodule-form.component.html: -------------------------------------------------------------------------------- 1 |
2 | 3 | 4 | Shipping Information 5 | 6 | 7 |
8 |
9 | 10 | 11 | 12 |
13 |
14 |
15 |
16 | 17 | 18 | 19 | First name is required 20 | 21 | 22 |
23 |
24 | 25 | 26 | 27 | Last name is required 28 | 29 | 30 |
31 |
32 |
33 |
34 | 35 | 36 | 37 | Address is required 38 | 39 | 40 |
41 |
42 |
43 |
44 | 47 |
48 |
49 |
50 |
51 | 52 | 53 | 54 |
55 |
56 |
57 |
58 | 59 | 60 | 61 | City is required 62 | 63 | 64 |
65 |
66 | 67 | 68 | 69 | {{ state.name }} 70 | 71 | 72 | 73 | State is required 74 | 75 | 76 |
77 |
78 |
79 |
80 | 81 | 83 | {{postalCode.value.length}} / 5 84 | 85 |
86 |
87 |
88 |
89 | 90 | Free Shipping 91 | Priority Shipping 92 | Next Day Shipping 93 | 94 |
95 |
96 |
97 | 98 | 99 | 100 |
101 |
102 | -------------------------------------------------------------------------------- /src/app/teaching-forms/address-ngmodule-form/address-ngmodule-form.component.scss: -------------------------------------------------------------------------------- 1 | .full-width { 2 | width: 100%; 3 | } 4 | 5 | .shipping-card { 6 | min-width: 120px; 7 | margin: 20px auto; 8 | } 9 | 10 | .mat-radio-button { 11 | display: block; 12 | margin: 5px 0; 13 | } 14 | 15 | .row { 16 | display: flex; 17 | flex-direction: row; 18 | } 19 | 20 | .col { 21 | flex: 1; 22 | margin-right: 20px; 23 | } 24 | 25 | .col:last-child { 26 | margin-right: 0; 27 | } 28 | -------------------------------------------------------------------------------- /src/app/teaching-forms/address-ngmodule-form/address-ngmodule-form.component.spec.ts: -------------------------------------------------------------------------------- 1 | import { waitForAsync, ComponentFixture, TestBed } from '@angular/core/testing'; 2 | import { ReactiveFormsModule } from '@angular/forms'; 3 | import { NoopAnimationsModule } from '@angular/platform-browser/animations'; 4 | import { MatButtonModule } from '@angular/material/button'; 5 | import { MatCardModule } from '@angular/material/card'; 6 | import { MatInputModule } from '@angular/material/input'; 7 | import { MatRadioModule } from '@angular/material/radio'; 8 | import { MatSelectModule } from '@angular/material/select'; 9 | 10 | import { AddressNgModuleFormComponent } from './address-ngmodule-form.component'; 11 | 12 | describe('AddressNgModuleFormComponent', () => { 13 | let component: AddressNgModuleFormComponent; 14 | let fixture: ComponentFixture; 15 | 16 | beforeEach(waitForAsync(() => { 17 | TestBed.configureTestingModule({ 18 | declarations: [ AddressNgModuleFormComponent ], 19 | imports: [ 20 | NoopAnimationsModule, 21 | ReactiveFormsModule, 22 | MatButtonModule, 23 | MatCardModule, 24 | MatInputModule, 25 | MatRadioModule, 26 | MatSelectModule, 27 | ] 28 | }).compileComponents(); 29 | })); 30 | 31 | beforeEach(() => { 32 | fixture = TestBed.createComponent(AddressNgModuleFormComponent); 33 | component = fixture.componentInstance; 34 | fixture.detectChanges(); 35 | }); 36 | 37 | it('should compile', () => { 38 | expect(component).toBeTruthy(); 39 | }); 40 | }); 41 | -------------------------------------------------------------------------------- /src/app/teaching-forms/address-ngmodule-form/address-ngmodule-form.component.ts: -------------------------------------------------------------------------------- 1 | import { Component } from '@angular/core'; 2 | import { FormBuilder, Validators } from '@angular/forms'; 3 | 4 | import { UsStates } from '@model'; 5 | 6 | /** NgModule version of Address Form generated by `ng generate @angular/material:address-form address-ngmodule-form` */ 7 | @Component({ 8 | selector: 'app-address-ngmodule-form', 9 | templateUrl: './address-ngmodule-form.component.html', 10 | styleUrls: ['./address-ngmodule-form.component.scss'] 11 | }) 12 | export class AddressNgModuleFormComponent { 13 | addressForm = this.fb.group({ 14 | company: null, 15 | firstName: [null, Validators.required], 16 | lastName: [null, Validators.required], 17 | address: [null, Validators.required], 18 | address2: null, 19 | city: [null, Validators.required], 20 | state: [null, Validators.required], 21 | postalCode: [null, Validators.compose([ 22 | Validators.required, Validators.minLength(5), Validators.maxLength(5)]) 23 | ], 24 | shipping: ['free', Validators.required] 25 | }); 26 | 27 | hasUnitNumber = false; 28 | 29 | states = UsStates; 30 | 31 | constructor(private fb: FormBuilder) { } 32 | 33 | onSubmit(): void { 34 | alert('Thank you!'); 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /src/app/teaching-forms/address-ngmodule-form/address.module.ts: -------------------------------------------------------------------------------- 1 | import { NgModule } from '@angular/core'; 2 | import { CommonModule } from '@angular/common'; 3 | import { ReactiveFormsModule } from '@angular/forms'; 4 | 5 | import { MatButtonModule } from '@angular/material/button'; 6 | import { MatCardModule } from '@angular/material/card'; 7 | import { MatInputModule } from '@angular/material/input'; 8 | import { MatRadioModule } from '@angular/material/radio'; 9 | import { MatSelectModule } from '@angular/material/select'; 10 | 11 | import { AddressNgModuleFormComponent } from './address-ngmodule-form.component'; 12 | 13 | @NgModule({ 14 | imports: [ 15 | CommonModule, 16 | ReactiveFormsModule, 17 | 18 | MatButtonModule, 19 | MatCardModule, 20 | MatInputModule, 21 | MatRadioModule, 22 | MatSelectModule, 23 | ], 24 | declarations: [ 25 | AddressNgModuleFormComponent 26 | ] 27 | }) 28 | export class AddressModule { } 29 | -------------------------------------------------------------------------------- /src/app/teaching-forms/company-general-form-no-widget/company-general-form-no-widget.component.html: -------------------------------------------------------------------------------- 1 |
2 | 3 | 4 | 5 | {{ input.errors['error'] }} 6 | 7 | 8 |
9 | -------------------------------------------------------------------------------- /src/app/teaching-forms/company-general-form-no-widget/company-general-form-no-widget.component.ts: -------------------------------------------------------------------------------- 1 | import { Component, Input } from '@angular/core'; 2 | 3 | import { Company } from '@model'; 4 | import { formContainerViewProvider } from '@core'; 5 | import { FORMS } from '@imports'; 6 | 7 | @Component({ 8 | selector: 'app-company-general-form', 9 | standalone: true, 10 | imports: [FORMS], 11 | templateUrl: './company-general-form-no-widget.component.html', 12 | viewProviders: [formContainerViewProvider], 13 | }) 14 | export class CompanyGeneralFormComponent { 15 | @Input() vm?: Partial; 16 | } 17 | -------------------------------------------------------------------------------- /src/app/teaching-forms/company-general-form-w-widget/company-general-form-w-widget.component.html: -------------------------------------------------------------------------------- 1 |
2 | 3 |
4 | -------------------------------------------------------------------------------- /src/app/teaching-forms/company-general-form-w-widget/company-general-form-w-widget.component.ts: -------------------------------------------------------------------------------- 1 | import { Component, Input } from '@angular/core'; 2 | 3 | import { Company } from '@model'; 4 | import { formContainerViewProvider } from '@core'; 5 | import { FORMS } from '@imports'; 6 | 7 | @Component({ 8 | selector: 'app-company-general-form', 9 | standalone: true, 10 | imports: [FORMS], 11 | templateUrl: './company-general-form-w-widget.component.html', 12 | viewProviders: [formContainerViewProvider], 13 | }) 14 | export class CompanyGeneralFormComponent { 15 | @Input() vm?: Partial; 16 | } 17 | -------------------------------------------------------------------------------- /src/app/teaching-forms/solo-address-form-reactive-w-val/solo-address-form.component.html: -------------------------------------------------------------------------------- 1 |
2 | 3 | 4 | Solo Address (Reactive - Model Validation) 5 | 6 | 7 |
8 |
9 | 10 | 11 | 12 | {{ addressForm.controls.street.errors['error'] }} 13 | 14 | 15 |
16 |
17 |
18 |
19 | 22 |
23 |
24 |
25 |
26 | 27 | 28 | 29 |
30 |
31 |
32 |
33 | 34 | 35 | 36 | {{ addressForm.controls.city.errors['error'] }} 37 | 38 | 39 |
40 |
41 | 42 | 43 | 44 | {{ state.name }} 45 | 46 | 47 | 48 | {{ addressForm.controls.state.errors['error'] }} 49 | 50 | 51 |
52 |
53 |
54 |
55 | 56 | 57 | 58 | {{ addressForm.controls.postalCode.errors['error'] }} 59 | 60 | 61 |
62 |
63 |
64 | 65 | 66 | 67 |
68 |
69 | -------------------------------------------------------------------------------- /src/app/teaching-forms/solo-address-form-reactive-w-val/solo-address-form.component.ts: -------------------------------------------------------------------------------- 1 | import { Component } from '@angular/core'; 2 | import { CommonModule } from '@angular/common'; 3 | import { FormBuilder, ReactiveFormsModule } from '@angular/forms'; 4 | import { MatButtonModule } from '@angular/material/button'; 5 | import { MatCardModule } from '@angular/material/card'; 6 | import { MatInputModule } from '@angular/material/input'; 7 | import { MatRadioModule } from '@angular/material/radio'; 8 | import { MatSelectModule } from '@angular/material/select'; 9 | 10 | import { Address, UsStates } from '@model'; 11 | import { addressSyncValidationSuite } from '@validators'; 12 | import { addValidatorsToControls } from '@validation'; 13 | 14 | @Component({ 15 | selector: 'app-address-form', 16 | standalone: true, 17 | templateUrl: './solo-address-form.component.html', 18 | imports: [ 19 | CommonModule, 20 | MatButtonModule, MatCardModule, MatInputModule, MatRadioModule, MatSelectModule, 21 | ReactiveFormsModule 22 | ], 23 | }) 24 | export class SoloAddressFormComponent { 25 | addressForm = this.fb.group({ 26 | street: null, 27 | street2: null, 28 | city: null, 29 | state: null, 30 | postalCode: null, 31 | }); 32 | 33 | hasStreet2 = false; 34 | 35 | states = UsStates; 36 | 37 | constructor(private fb: FormBuilder) { 38 | addValidatorsToControls(this.addressForm.controls, addressSyncValidationSuite); 39 | } 40 | 41 | /** DEMO: validate the address reactive form and display aspects of it in the browser console */ 42 | showValidationState(): void { 43 | console.groupCollapsed('Address Reactive Form Validation State'); 44 | addressSyncValidationSuite.reset(); 45 | const r = addressSyncValidationSuite(this.addressForm.value as unknown as Address); 46 | console.log('address form validation state', r); 47 | const errors = r.getErrors(); 48 | console.log('errors', errors); 49 | console.groupEnd(); 50 | const errorCount = Object.keys(errors).length; 51 | alert(`Has ${errorCount ? errorCount : 'no'} errors. Look at browser console.`); 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /src/app/teaching-forms/solo-address-form-reactive/solo-address-form.component.html: -------------------------------------------------------------------------------- 1 |
2 | 3 | 4 | Solo Address (Reactive - UI Validation) 5 | 6 | 7 |
8 |
9 | 10 | 11 | 12 | Address is required 13 | 14 | 15 |
16 |
17 |
18 |
19 | 22 |
23 |
24 |
25 |
26 | 27 | 28 | 29 |
30 |
31 |
32 |
33 | 34 | 35 | 36 | City is required 37 | 38 | 39 |
40 |
41 | 42 | 43 | 44 | {{ state.name }} 45 | 46 | 47 | 48 | State is required 49 | 50 | 51 |
52 |
53 |
54 |
55 | 56 | 57 | {{postalCode.value.length}} / 5 58 | 59 | Postal Code is required 60 | 61 | 62 | Postal Code must be five digits 63 | 64 | 65 |
66 |
67 |
68 | 69 | 70 | 71 |
72 |
73 | -------------------------------------------------------------------------------- /src/app/teaching-forms/solo-address-form-reactive/solo-address-form.component.ts: -------------------------------------------------------------------------------- 1 | import { Component } from '@angular/core'; 2 | import { CommonModule } from '@angular/common'; 3 | import { FormBuilder, ReactiveFormsModule, Validators } from '@angular/forms'; 4 | import { MatButtonModule } from '@angular/material/button'; 5 | import { MatCardModule } from '@angular/material/card'; 6 | import { MatInputModule } from '@angular/material/input'; 7 | import { MatRadioModule } from '@angular/material/radio'; 8 | import { MatSelectModule } from '@angular/material/select'; 9 | 10 | import { UsStates } from '@model'; 11 | 12 | @Component({ 13 | selector: 'app-address-form', 14 | standalone: true, 15 | templateUrl: './solo-address-form.component.html', 16 | imports: [ 17 | CommonModule, 18 | MatButtonModule, MatCardModule, MatInputModule, MatRadioModule, MatSelectModule, 19 | ReactiveFormsModule 20 | ], 21 | }) 22 | export class SoloAddressFormComponent { 23 | addressForm = this.fb.group({ 24 | address: [null, Validators.required], 25 | address2: null, 26 | city: [null, Validators.required], 27 | state: [null, Validators.required], 28 | postalCode: [null, Validators.compose([ 29 | Validators.required, Validators.minLength(5), Validators.maxLength(5)]) 30 | ], 31 | }); 32 | 33 | hasAddress2 = false; 34 | 35 | states = UsStates; 36 | 37 | constructor(private fb: FormBuilder) { 38 | } 39 | 40 | /** DEMO: validate the address reactive form and display aspects of it in the browser console */ 41 | showValidationState(): void { 42 | console.groupCollapsed('Address Reactive Form Validation State'); 43 | this.addressForm.markAllAsTouched(); 44 | console.log('ngForm.controls', this.addressForm.controls); 45 | const errors = this.addressForm.errors ?? {}; 46 | console.log('errors', errors); 47 | console.groupEnd(); 48 | const errorCount = Object.keys(errors).length; 49 | alert(`Has ${errorCount ? errorCount : 'no'} errors. Look at browser console.`); 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /src/app/validation/form-field-ng-model.directive.ts: -------------------------------------------------------------------------------- 1 | import { Directive, Inject, Input, OnChanges, OnDestroy, Optional } from '@angular/core'; 2 | import { NgModel } from '@angular/forms'; 3 | import { Subscription } from 'rxjs'; 4 | 5 | import { FormValidationScopeDirective } from './form-validation-scope.directive' 6 | import { Indexable } from '@core'; 7 | import { 8 | AsyncValidationSuiteFactories, ASYNC_VALIDATION_SUITE_FACTORIES, 9 | SYNC_VALIDATION_SUITES, SyncValidationSuites 10 | } from './interfaces'; 11 | import { ValidationContext, VALIDATION_CONTEXT } from './validation-context'; 12 | import { vestAsyncFieldValidator, vestSyncFieldValidator } from './validation-fns'; 13 | 14 | /** Sets validators for Template-Driven controls using NgModel 15 | * Skipped if element with `[ngModel]` also has `no-val` attribute 16 | */ 17 | @Directive({ 18 | // eslint-disable-next-line @angular-eslint/directive-selector 19 | selector: '[ngModel]:not([no-val])', 20 | standalone: true, 21 | }) 22 | export class FormFieldNgModelDirective implements OnChanges, OnDestroy { 23 | 24 | /** Context that validators may reference for external information and services. 25 | * Blended with global ValidationContext and parent FormValidationModelDirective context. 26 | * Optional. 27 | */ 28 | @Input() context?: ValidationContext; 29 | 30 | /** Field name to validate. Should be a property of the model. 31 | * If not specified, will use the NgModel control's name (value of the `name` attribute). 32 | */ 33 | @Input() field?: string; 34 | 35 | /** Group name of tests within the validation suite. 36 | * If not specified, try to pick up from parent FormValidationModelDirective. 37 | * If there is a group name, only process tests in that group. 38 | */ 39 | @Input() group?: string; 40 | 41 | /** Data model whose properties will be validated. 42 | * If not specified, try to pick up from parent FormValidationModelDirective. 43 | */ 44 | @Input() model?: Indexable; 45 | 46 | /** Name of the type of model to be validated. Identifies the suite of validators to apply. 47 | * If not specified, try to pick up from parent FormValidationModelDirective. 48 | * Required for validation. 49 | */ 50 | @Input() modelType?: string; 51 | 52 | private scopeSub?: Subscription; 53 | 54 | constructor( 55 | @Optional() private formValidationScope: FormValidationScopeDirective, 56 | @Optional() @Inject(ASYNC_VALIDATION_SUITE_FACTORIES) private asyncValidationSuiteFactories: AsyncValidationSuiteFactories, 57 | @Optional() @Inject(SYNC_VALIDATION_SUITES) private syncValidationSuites: SyncValidationSuites, 58 | @Optional() @Inject(VALIDATION_CONTEXT) private globalContext: ValidationContext, 59 | /** Form control for the ngModel directive */ 60 | private ngModel: NgModel, 61 | ) { 62 | if (formValidationScope) { 63 | // (re)setup validation if the validation scope was updated. 64 | this.scopeSub = this.formValidationScope.changed.subscribe(_ => this.ngOnChanges()); 65 | } 66 | } 67 | 68 | ngOnChanges(): void { 69 | if (!this.syncValidationSuites || !this.asyncValidationSuiteFactories) { 70 | throw 'FormFieldNgModelDirective: cannot validate because there are no registered validation suites.'; 71 | } 72 | 73 | const ngModelControl = this.ngModel.control; 74 | 75 | const field = this.field || this.ngModel.name; // if no field name, assume the name of the control is the field name. 76 | const modelType = this.modelType || this.formValidationScope?.modelType; 77 | 78 | const model = this.model ?? this.formValidationScope?.model; 79 | 80 | if (!field || !model || !modelType) { 81 | // Must have the field, model, and modelType to add a validator. 82 | ngModelControl._validationMetadata = undefined; // NOT adding validators 83 | return; 84 | } 85 | 86 | // Blend contexts with more local context (ex: this.context) taking precedence. 87 | const context = { ...this.globalContext, ...this.formValidationScope?.context, ...this.context }; 88 | const group = this.group || this.formValidationScope?.group; 89 | ngModelControl._validationMetadata = { field, modelType }; 90 | 91 | const suite = this.syncValidationSuites[modelType]; 92 | if (!!suite) { 93 | const validator = vestSyncFieldValidator(suite, field, model, group, context); 94 | ngModelControl.clearValidators(); 95 | ngModelControl.addValidators(validator); 96 | } 97 | 98 | /* Async suite factory creates a vest suite of async validations for the given model type 99 | * 100 | * Each async validator needs its own instance of the async vest suite. 101 | * You can only call `done()` once per suite invocation. 102 | * If you call `done()` twice while an async operation is flight, 103 | * that operation's resolution will not be caught by the later `done()`. 104 | * So we need to isolate suite instances. 105 | */ 106 | const asyncSuiteFactory = this.asyncValidationSuiteFactories[modelType]; 107 | if (!!asyncSuiteFactory) { 108 | const asyncSuite = asyncSuiteFactory(); 109 | const validator = vestAsyncFieldValidator(asyncSuite, field, model, group, context); 110 | ngModelControl.clearAsyncValidators(); 111 | ngModelControl.addAsyncValidators(validator); 112 | } 113 | 114 | ngModelControl.updateValueAndValidity(); 115 | } 116 | 117 | ngOnDestroy(): void { 118 | this.scopeSub?.unsubscribe(); 119 | } 120 | } 121 | -------------------------------------------------------------------------------- /src/app/validation/form-validation-scope.directive.ts: -------------------------------------------------------------------------------- 1 | import { Directive, Input, OnChanges, SimpleChanges } from '@angular/core'; 2 | import { Subject } from 'rxjs'; 3 | import { ValidationContext } from './interfaces'; 4 | 5 | import { Indexable } from '@utils'; 6 | 7 | /** Set the validation scope variables on a form, ngModelGroup, or an element with a `val-model` attribute. 8 | * Must specify model and modelType to match this directive. 9 | */ 10 | @Directive({ 11 | // eslint-disable-next-line @angular-eslint/directive-selector 12 | selector: 'form[model][modelType]:not([ngNoForm]):not([formGroup]),ng-form[model][modelType],[ngForm][model][modelType],[ngModelGroup][model][modelType],[val-model]', 13 | standalone: true, 14 | }) 15 | export class FormValidationScopeDirective implements OnChanges { 16 | /** data model whose properties will be validated. Required. */ 17 | @Input() model: Indexable | undefined; 18 | 19 | /** Name of the type of model to be validated. Identifies the suite of validators to apply. Required. */ 20 | @Input() modelType: string | undefined; 21 | 22 | /** Group name of tests within the validation suite. Only process tests in that group. */ 23 | @Input() group?: string; 24 | 25 | /** Context that validators may reference for external information and services. */ 26 | @Input() context?: ValidationContext; 27 | 28 | private changeSubject = new Subject(); 29 | 30 | /** Observable that emits when any of the validation scope inputs changed. */ 31 | changed = this.changeSubject.asObservable(); 32 | 33 | ngOnChanges(_changes: SimpleChanges): void { 34 | this.changeSubject.next(null); 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /src/app/validation/index.ts: -------------------------------------------------------------------------------- 1 | export * from './form-field-ng-model.directive'; 2 | export * from './form-validation-scope.directive'; 3 | export * from './interfaces'; 4 | export * from './validation-context'; 5 | export * from './validation-fns'; 6 | export * from './validation-fns-reactive'; 7 | -------------------------------------------------------------------------------- /src/app/validation/interfaces.ts: -------------------------------------------------------------------------------- 1 | import { InjectionToken } from '@angular/core'; 2 | import { Indexable } from '@utils'; 3 | import { Suite } from 'vest'; 4 | 5 | export const ASYNC_VALIDATION_SUITE_FACTORIES = new InjectionToken('Async Validation Suite Factories'); 6 | export const SYNC_VALIDATION_SUITES = new InjectionToken('Synchronous Validation Suites'); 7 | 8 | /** Creates AsyncValidationSuite */ 9 | export type AsyncValidationSuiteFactory = () => ValidationSuite; 10 | 11 | /** Map of asynchronous vest validation suite factories (creators), keyed by model type. */ 12 | export interface AsyncValidationSuiteFactories extends Indexable { 13 | } 14 | 15 | /** Map of synchronous vest validation suites, keyed by model type. */ 16 | export interface SyncValidationSuites extends Indexable { 17 | } 18 | 19 | /** A vest sync or async validation suite, shaped for this validation implementation. */ 20 | export type ValidationSuite = Suite; 21 | 22 | /** Vest validation suite function. Pass to vest `create()` to make a vest suite. */ 23 | export type ValidationSuiteFn = ( 24 | model: Indexable, 25 | field?: string, 26 | group?: string, 27 | vc?: ValidationContext 28 | ) => void; 29 | 30 | /** Global context with properties and services for use by validations. 31 | * For example, it could contain a cache of other entities to reference. 32 | * Each application can/should implement as needed and inject with the VALIDATION_CONTEXT injection token 33 | */ 34 | export interface ValidationContext extends Indexable { 35 | } 36 | -------------------------------------------------------------------------------- /src/app/validation/validation-context.ts: -------------------------------------------------------------------------------- 1 | import { InjectionToken } from '@angular/core'; 2 | 3 | import { ValidationContext } from './interfaces'; 4 | export { ValidationContext }; 5 | 6 | /** Injection token for the global validation context. The app can implement and provide with this token. */ 7 | export const VALIDATION_CONTEXT = new InjectionToken('ValidationContext'); 8 | -------------------------------------------------------------------------------- /src/app/validation/validation-fns-reactive.ts: -------------------------------------------------------------------------------- 1 | import { FormControl } from '@angular/forms'; 2 | 3 | import { Indexable } from '@utils'; 4 | import { AsyncValidationSuiteFactory, ValidationContext, ValidationSuite } from './interfaces'; 5 | import { vestAsyncFieldValidator, vestSyncFieldValidator} from './validation-fns' 6 | 7 | /** Create and add Angular Validators to all the given form controls. 8 | * Useful primarily in Reactive Forms. 9 | * @param controlGroup an object whose properties are the field names and values are FormControls. 10 | * ex: an Angular `FormGroup`. Note can only be one level deep and not include FormArrays. 11 | * @param syncSuite the vest suite with synchronous validation rules 12 | * @param [asyncSuiteFactory] optional creator of vest suite with asynchronous validation rules 13 | * @param [model] the model data to validate or a function returning such a model 14 | * @param [context] global contextual data passed to vest validation rules. 15 | * @param [group] the name of a group of tests; only process tests in this group. 16 | */ 17 | export function addValidatorsToControls( 18 | controlGroup: Indexable, 19 | syncSuite: ValidationSuite, 20 | asyncSuiteFactory?: AsyncValidationSuiteFactory, 21 | model?: Indexable, 22 | context?: ValidationContext, 23 | group?: string, 24 | ) { 25 | Object.entries(controlGroup).forEach(([field, control]) => { 26 | const validator = vestSyncFieldValidator(syncSuite, field, model, group, context); 27 | control.clearValidators(); // start over 28 | control.addValidators(validator); 29 | 30 | if (asyncSuiteFactory) { 31 | const asyncSuite = asyncSuiteFactory(); 32 | const validator = vestAsyncFieldValidator(asyncSuite, field, model, group, context); 33 | control.clearAsyncValidators(); // start over 34 | control.addAsyncValidators(validator); 35 | } 36 | }); 37 | } 38 | 39 | -------------------------------------------------------------------------------- /src/app/validation/validation-fns.ts: -------------------------------------------------------------------------------- 1 | import { AbstractControl, AsyncValidatorFn, ValidationErrors, ValidatorFn, Validators } from '@angular/forms'; 2 | 3 | import { Indexable } from '@utils'; 4 | import { ValidationContext, ValidationSuite } from './interfaces'; 5 | 6 | /** Create Angular synchronous validator function for a single field of the model in the validation context. 7 | * When validation fails, the function returns a validation errors with two properties: 8 | * `error` - the first vest validation error, 9 | * `errors` - all of the vest validation errors for that field. 10 | * @param suite the vest suite with validation rules 11 | * @param field to validate 12 | * @param [model] the view model data to validate or a function returning such a model 13 | * Merges the control.value as the field property of that model. 14 | * @param [group] the name of a group of tests; only process tests in this group. 15 | * @param [context] global contextual data passed to vest validation rules. 16 | */ 17 | export function vestSyncFieldValidator( 18 | suite: ValidationSuite, // the validations 19 | field: string, // the property to validate 20 | model?: Indexable | (() => Indexable), // the view model with the data to validate 21 | group?: string, // the group of properties to validate (if specified) 22 | context?: ValidationContext, // extra stuff validators could use 23 | ): ValidatorFn | ValidatorFn[] { 24 | const vestValidator = (control: AbstractControl): ValidationErrors | null => { 25 | let mod: Indexable = typeof model == 'function' ? model() : model; 26 | // Merge `control.value` because ngModel will not have updated the viewModel yet. 27 | mod = { ...mod, [field]: control.value }; 28 | const result = suite(mod, field, group, context).getErrors(); 29 | const errors = result[field]; 30 | return errors ? { error: errors[0], errors } : null; 31 | }; 32 | 33 | // HACK to find out if the field is required. 34 | // Angular Material looks for an Angular required validator and draws the component label accordingly. 35 | // So if we discover that the field is required, "compose" with that Angular required validator 36 | const testRun = suite({ [field]: null }, field, group, context).getErrors(); 37 | const isRequired = (testRun[field] ?? []).some(err => err.includes('is required')); 38 | return isRequired ? [vestValidator, Validators.required] : vestValidator; 39 | } 40 | 41 | /** Create Angular asynchronous validator function for a single field of the model in the validation context 42 | * When validation fails, the function returns a validation errors with two properties: 43 | * `error` - the first vest validation error, 44 | * `errors` - all of the vest validation errors for that field. 45 | * @param suite that creates the vest suite with async validation rules. 46 | * @param field to validate 47 | * @param [model] the view model data to validate or a function returning such a model 48 | * Merges the control.value as the field property of that model. 49 | * @param [group] the name of a group of tests; only process tests in this group. 50 | * @param [context] global contextual data passed to vest validation rules. 51 | * 52 | * The must be a unique instance! 53 | * 54 | * Each async validator needs its own instance of the async vest suite. 55 | * You can only call `done()` once per suite invocation. 56 | * If you call `done()` twice while an async operation is flight, 57 | * that operation's resolution will not be caught by the later `done()`. 58 | * So we need to isolate suite instances. 59 | */ 60 | export function vestAsyncFieldValidator( 61 | suite: ValidationSuite, 62 | field: string, 63 | model?: Indexable | (() => Indexable), 64 | group?: string, 65 | context?: ValidationContext, 66 | ): AsyncValidatorFn { 67 | // console.log(`*** Creating vestAsyncValidator for field ${field}`) 68 | const vestAsyncValidator = (control: AbstractControl): Promise => { 69 | const promise = new Promise((resolve) => { 70 | // console.log(`async validator for ${field} started`); 71 | let mod: Indexable = typeof model == 'function' ? model() : model 72 | // Merge control.value because ngModel will not have updated the viewModel yet. 73 | mod = { ...mod, [field]: control.value }; 74 | suite(mod, field, group, context) 75 | .done(field, result => { 76 | // console.log(`async validator for ${field} resolved`); 77 | const errors = result.getErrors()[field]; 78 | resolve(errors ? { error: errors[0], errors } : null); 79 | }) 80 | // Catch case where the field has no async validations 81 | .done(_result => { 82 | // All validations complete. Resolve w/o error. 83 | // Harmless if field DID have async validation and resolved earlier 84 | // because this second call to `resolve` would do nothing. 85 | // But if the field did NOT have an async validation, 86 | // the earlier field resolve would not have been called and 87 | // the field status would be "PENDING" forever. 88 | // Example: comment out all async validations for "legalName". 89 | resolve(null); 90 | }); 91 | }) 92 | return promise; 93 | }; 94 | return vestAsyncValidator; 95 | } 96 | -------------------------------------------------------------------------------- /src/app/validation/validation.d.ts: -------------------------------------------------------------------------------- 1 | import { Indexable } from '@utils'; 2 | 3 | declare module '@angular/forms' { 4 | /** Extend features of the Angular AbstractControl class. */ 5 | interface AbstractControl { 6 | /** Metadata about the validation added by FormFieldNgModelDirective. For unit testing. */ 7 | _validationMetadata?: { field: string, modelType: string }; 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /src/app/validators/address.sync-validations.spec.ts: -------------------------------------------------------------------------------- 1 | import { addressSyncValidationSuite } from './address.sync-validations'; 2 | import { customVestSuiteResultMatchers, disabledState, supportedState } from './unit-test-validation-helpers'; 3 | import { syncValidationSuites } from './validation-suites'; 4 | 5 | describe('addressSyncValidationSuite', () => { 6 | beforeEach(() => { 7 | jasmine.addMatchers(customVestSuiteResultMatchers) 8 | }); 9 | 10 | it('is registered with syncValidationSuites', () => { 11 | expect(syncValidationSuites['address']).toBe(addressSyncValidationSuite); 12 | }) 13 | 14 | it('has errors when address model is empty', () => { 15 | const result = addressSyncValidationSuite({}); 16 | expect(result.hasErrors()).toBeTrue(); 17 | }); 18 | 19 | describe('when street', () => { 20 | it('is a good street it passes', () => { 21 | const result = addressSyncValidationSuite({ street: '123 main' }); 22 | expect(result).hasNoFieldErrors('street'); 23 | }); 24 | 25 | it('is null it has a required error', () => { 26 | const result = addressSyncValidationSuite({ street: null }); 27 | expect(result).hasExpectedFieldError('street', /required/); 28 | }); 29 | 30 | it('is empty it has a required error', () => { 31 | const result = addressSyncValidationSuite({ street: '' }); 32 | expect(result).hasExpectedFieldError('street', /required/ ); 33 | }); 34 | 35 | it('is fewer than 3 chars it has the expected min length error', () => { 36 | const result = addressSyncValidationSuite({ street: '12' }); 37 | expect(result).hasExpectedFieldError('street', /at least 3/ ); 38 | }); 39 | 40 | it('is more than 50 chars it has the expected max length error', () => { 41 | const result = addressSyncValidationSuite({ street: ' 234567890 234567890 234567890 234567890 !TOO LONG!' }); 42 | expect(result).hasExpectedFieldError('street', /at most 50/ ); 43 | }) 44 | }); 45 | 46 | describe('when street2', () => { 47 | // There should be no restrictions on Street2 48 | it('is provided it passes', () => { 49 | const result = addressSyncValidationSuite({ street2: 'Apt. A' }); 50 | expect(result).hasNoFieldErrors('street2'); 51 | }); 52 | 53 | it('is null it passes', () => { 54 | const result = addressSyncValidationSuite({ street2: null }); 55 | expect(result).hasNoFieldErrors('street2'); 56 | }); 57 | 58 | it('is empty it passes', () => { 59 | const result = addressSyncValidationSuite({ street2: '' }); 60 | expect(result).hasNoFieldErrors('street2'); 61 | }); 62 | }); 63 | 64 | describe('when city',() => { 65 | it('is provided it passes', () => { 66 | const result = addressSyncValidationSuite({ city: 'small town' }); 67 | expect(result).hasNoFieldErrors('city'); 68 | }); 69 | 70 | it('is null it has a required error', () => { 71 | const result = addressSyncValidationSuite({ city: null }); 72 | expect(result).hasExpectedFieldError('city', /required/ ); 73 | }); 74 | 75 | it('is empty it has a required error', () => { 76 | const result = addressSyncValidationSuite({ city: '' }); 77 | expect(result).hasExpectedFieldError('city', /required/ ); 78 | }); 79 | }); 80 | 81 | describe('when state',() => { 82 | it('is one of the enabled U.S. States it passes', () => { 83 | const result = addressSyncValidationSuite({ state: supportedState?.abbreviation }); 84 | expect(result).hasNoFieldErrors('state'); 85 | }); 86 | 87 | it('is one of the disabled U.S. States it has the expected error', () => { 88 | const result = addressSyncValidationSuite({ state: disabledState?.abbreviation }); 89 | expect(result).hasExpectedFieldError('state', /supported/ ); 90 | }); 91 | 92 | it('is null it has a required error', () => { 93 | const result = addressSyncValidationSuite({ state: null }); 94 | expect(result).hasExpectedFieldError('state', /required/ ); 95 | }); 96 | 97 | it('is empty it has a required error', () => { 98 | const result = addressSyncValidationSuite({ state: '' }); 99 | expect(result).hasExpectedFieldError('state', /required/ ); 100 | }); 101 | }); 102 | 103 | describe('when postal code', () => { 104 | it('is 5 digits it passes', () => { 105 | const result = addressSyncValidationSuite({ postalCode: '12345' }); 106 | expect(result).hasNoFieldErrors('postalCode'); 107 | }); 108 | 109 | it('is zip+4 it passes', () => { 110 | const result = addressSyncValidationSuite({ postalCode: '12345-1234' }); 111 | expect(result).hasNoFieldErrors('postalCode'); 112 | }); 113 | 114 | it('is null it has a required error', () => { 115 | const result = addressSyncValidationSuite({ postalCode: null }); 116 | expect(result).hasExpectedFieldError('postalCode', /required/ ); 117 | }); 118 | 119 | it('is empty it has a required error', () => { 120 | const result = addressSyncValidationSuite({ postalCode: '' }); 121 | expect(result).hasExpectedFieldError('postalCode', /required/ ); 122 | }); 123 | 124 | it('has non-digits it has a format error', () => { 125 | const result = addressSyncValidationSuite({ postalCode: 'abcde' }); 126 | expect(result).hasExpectedFieldError('postalCode', /must be 5 digit/ ); 127 | }); 128 | 129 | it('has zip+4 without the dash it has a format error', () => { 130 | const result = addressSyncValidationSuite({ postalCode: '123451234' }); 131 | expect(result).hasExpectedFieldError('postalCode', /must be 5 digit/ ); 132 | }); 133 | }); 134 | }); 135 | -------------------------------------------------------------------------------- /src/app/validators/address.sync-validations.ts: -------------------------------------------------------------------------------- 1 | import { create, enforce, omitWhen, only, test } from 'vest'; 2 | 3 | import { Address, UsStates } from '@model'; 4 | import { ValidationContext, ValidationSuite, ValidationSuiteFn } from '@validation'; 5 | 6 | export const addressSyncValidationSuite: ValidationSuite = 7 | create('AddressSyncValidationSuite', 8 | (model: Partial
, field?: string, groupName?: string, context?: ValidationContext) => { 9 | only(field); // if field defined, limit to tests of this field 10 | addressSyncValidations(model, field, groupName, context); 11 | }); 12 | 13 | export const addressSyncValidations: ValidationSuiteFn = (model: Partial
) => { 14 | model = model ?? {}; 15 | 16 | test('street', 'Street is required', () => { 17 | enforce(model.street).isNotBlank(); 18 | }); 19 | 20 | omitWhen(!model.street, () => { 21 | test('street', 'Street must be at least 3 characters long', () => { 22 | enforce(model.street).longerThanOrEquals(3); 23 | }); 24 | 25 | test('street', 'Street may be at most 50 characters long', () => { 26 | enforce(model.street).shorterThanOrEquals(50); 27 | }); 28 | }); 29 | 30 | test('city', 'City is required', () => { 31 | enforce(model.city).isNotBlank(); 32 | }); 33 | 34 | test('state', 'State is required', () => { 35 | enforce(model.state).isNotBlank(); 36 | }); 37 | 38 | test('state', 'State must be one of the supported US states', () => { 39 | enforce(model.state).condition((state: string) => 40 | UsStates.some(s => s.abbreviation === state && !s.disabled)); 41 | }); 42 | 43 | test('postalCode', 'Postal Code is required', () => { 44 | enforce(model.postalCode).isNotBlank(); 45 | }); 46 | 47 | omitWhen(!model.postalCode, () => { 48 | test('postalCode', 'Postal Code must be 5 digit zip (12345) or a zip+4 (12345-1234)', () => { 49 | enforce(model.postalCode).isPostalCode('US'); 50 | }); 51 | }); 52 | } 53 | -------------------------------------------------------------------------------- /src/app/validators/app-validation-context.ts: -------------------------------------------------------------------------------- 1 | import { inject, Provider} from '@angular/core'; 2 | 3 | import { FeinValidationService } from '@services'; 4 | import { ValidationContext, VALIDATION_CONTEXT } from '@validation'; 5 | 6 | /** Global context for use by validations in this application. 7 | * Provided in `main.ts` with VALIDATION_CONTEXT injection token. 8 | */ 9 | export interface AppValidationContext extends ValidationContext { 10 | feinValidationService: FeinValidationService 11 | } 12 | 13 | /** Provider of the global context for use by validations in this application. Provide in `main.ts`.*/ 14 | export const appValidationContextProvider: Provider = { provide: VALIDATION_CONTEXT, useFactory: () => { 15 | const feinValidationService = inject(FeinValidationService); 16 | return { 17 | feinValidationService 18 | } as AppValidationContext; 19 | }}; 20 | 21 | 22 | 23 | -------------------------------------------------------------------------------- /src/app/validators/company.async-validations.spec.ts: -------------------------------------------------------------------------------- 1 | import { asyncValidationSuiteFactories } from './validation-suites'; 2 | import { createCompanyAsyncValidationSuite } from './company.async-validations'; 3 | import { customVestSuiteResultMatchers, testAppContext } from './unit-test-validation-helpers'; 4 | import { ValidationSuite } from '@validation'; 5 | 6 | describe('companyAsyncValidationSuite', () => { 7 | let companyAsyncValidationSuite: ValidationSuite ; 8 | 9 | beforeEach(() => { 10 | jasmine.addMatchers(customVestSuiteResultMatchers); 11 | companyAsyncValidationSuite = createCompanyAsyncValidationSuite(); 12 | }); 13 | 14 | describe('createCompanyAsyncValidationSuite', () => { 15 | it('is registered with asyncValidationSuiteFactories', () => { 16 | expect(asyncValidationSuiteFactories['company']).toBe(createCompanyAsyncValidationSuite); 17 | }); 18 | 19 | it('creates a "companyAsyncValidationSuite"', () => { 20 | expect(companyAsyncValidationSuite).toBeDefined(); 21 | }); 22 | }) 23 | 24 | describe('when fein', () => { 25 | it('is registered with the IRS, it passes', (done) => { 26 | companyAsyncValidationSuite( { fein: '13-1234567' }, 'fein', undefined, testAppContext) 27 | .done(result => { 28 | expect(result).hasNoFieldErrors('fein'); 29 | done(); 30 | }) 31 | }); 32 | 33 | it('is not registered with the IRS, it has the expected error', (done) => { 34 | companyAsyncValidationSuite( { fein: '66-1234567' }, 'fein', undefined, testAppContext) 35 | .done(result => { 36 | expect(result).hasExpectedFieldError('fein', /not registered/); 37 | done(); 38 | }) 39 | }); 40 | 41 | it('is empty, it passes', (done) => { 42 | companyAsyncValidationSuite( { fein: '' }, 'fein', undefined, testAppContext) 43 | .done(result => { 44 | expect(result.hasErrors()).toBeFalse(); 45 | done(); 46 | }) 47 | }); 48 | 49 | it('is badly formed, it passes', (done) => { 50 | companyAsyncValidationSuite( { fein: 'no good' }, 'fein', undefined, testAppContext) 51 | .done(result => { 52 | expect(result.hasErrors()).toBeFalse(); 53 | done(); 54 | }) 55 | }); 56 | }); 57 | 58 | describe('when legal name', () => { 59 | it('matches the name registered with the IRS, it passes', (done) => { 60 | companyAsyncValidationSuite( { fein: '13-1234567', legalName: 'MARVELOUS PRODUCTS, INC.' }, 'legalName', undefined, testAppContext) 61 | .done(result => { 62 | expect(result).hasNoFieldErrors('legalName'); 63 | done(); 64 | }) 65 | }); 66 | 67 | it('does not exactly match the name registered with the IRS, it has the "not matched" error', (done) => { 68 | companyAsyncValidationSuite( { fein: '13-1234567', legalName: 'MARVELOUS PRODUCTS' }, 'legalName', undefined, testAppContext) 69 | .done(result => { 70 | expect(result).hasExpectedFieldError('legalName', /not match/); 71 | done(); 72 | }) 73 | }); 74 | 75 | it('is empty, it passes even if FEIN is registered', (done) => { 76 | companyAsyncValidationSuite( { fein: '13-1234567', legalName: '' }, 'legalName', undefined, testAppContext) 77 | .done(result => { 78 | expect(result).hasNoFieldErrors('legalName'); 79 | done(); 80 | }) 81 | }); 82 | 83 | it('is provided but the FEIN is not registered with the IRS, it passes', (done) => { 84 | companyAsyncValidationSuite( { fein: '66-1234567', legalName: 'any name' }, 'legalName', undefined, testAppContext) 85 | .done(result => { 86 | expect(result).hasNoFieldErrors('legalName'); 87 | done(); 88 | }) 89 | }); 90 | }); 91 | }); 92 | -------------------------------------------------------------------------------- /src/app/validators/company.async-validations.ts: -------------------------------------------------------------------------------- 1 | import { create, enforce, group, only, test, omitWhen } from 'vest'; 2 | 3 | import { AppValidationContext } from './app-validation-context'; 4 | import { Company } from '@model'; 5 | import { 6 | FeinValidationResponse, 7 | isGoodFein, 8 | } from '@services/fein-validation.service'; 9 | import { 10 | ValidationContext, 11 | ValidationSuite, 12 | ValidationSuiteFn, 13 | } from '@validation'; 14 | 15 | export function createCompanyAsyncValidationSuite() { 16 | return create('CompanyAsyncValidationSuite', ( 17 | model: Partial, 18 | field?: string, 19 | groupName?: string, 20 | context?: ValidationContext 21 | ) => { 22 | only(field); // if field defined, limit to tests of this field 23 | only.group(groupName); // if groupName defined, limit to tests of this group 24 | group('company', () => 25 | companyAsyncValidations(model, field, groupName, context) 26 | ); 27 | } 28 | ) as ValidationSuite; 29 | } 30 | 31 | export const companyAsyncValidationSuite: ValidationSuite = 32 | createCompanyAsyncValidationSuite(); 33 | 34 | /** Company Asynchronous Validation Suite */ 35 | export const companyAsyncValidations: ValidationSuiteFn = ( 36 | /** The object with data to validate */ 37 | model: Partial, 38 | /** The property of that data to validate, if we only want to validate one property */ 39 | field?: string, 40 | /** The group of properties in that data to validate, if we only want to validate one group */ 41 | groupName?: string, 42 | /** Extra resources that a validator might need */ 43 | context?: ValidationContext 44 | ) => { 45 | model = model ?? {}; 46 | 47 | const fvs = (context)?.feinValidationService; 48 | /** FEIN check function (or FN returning "not found" result) */ 49 | const checkFein = fvs 50 | ? fvs.check.bind(fvs) 51 | : // No fvs? This is almost certainly a bug. Remember to provide a context. 52 | (fein: string) => Promise.resolve({ fein }); 53 | 54 | omitWhen(!isGoodFein(model.fein), () => { 55 | // these validations will be completely omitted if the FEIN is not valid 56 | 57 | test('fein', 'Tax Number is not registered with the IRS', async () => { 58 | const response = await checkFein(model.fein!); 59 | // console.log('fein checkFein response', response); 60 | enforce(response.feinName).isNotNullish(); 61 | }); 62 | 63 | test('legalName', 'Legal Name must match Federal Tax Name', async () => { 64 | if (model.legalName) { 65 | const response = await checkFein(model.fein!); 66 | // console.log('legal name checkFein response', response); 67 | const name = response.feinName; 68 | 69 | enforce(name) 70 | .message( 71 | `Does not match the name, "${name}", registered with the IRS for this tax number` 72 | ) 73 | .condition(name => !name || name === '*' || name === model.legalName!.toUpperCase()); 74 | } 75 | }); 76 | }); 77 | }; 78 | -------------------------------------------------------------------------------- /src/app/validators/company.sync-validations.spec.ts: -------------------------------------------------------------------------------- 1 | import { Address } from '@model'; 2 | import { companySyncValidationSuite } from './company.sync-validations'; 3 | import { customVestSuiteResultMatchers } from './unit-test-validation-helpers'; 4 | import { syncValidationSuites } from './validation-suites'; 5 | 6 | describe('companySyncValidationSuite', () => { 7 | beforeEach(() => { 8 | jasmine.addMatchers(customVestSuiteResultMatchers) 9 | }); 10 | 11 | it('is registered with syncValidationSuites', () => { 12 | expect(syncValidationSuites['company']).toBe(companySyncValidationSuite); 13 | }) 14 | 15 | it('has errors when company model is empty', () => { 16 | const result = companySyncValidationSuite({}); 17 | expect(result.hasErrors()).toBeTrue(); 18 | }); 19 | 20 | describe('when legal name', () => { 21 | it('is a good name it passes', () => { 22 | const result = companySyncValidationSuite({ legalName: 'Acme' }); 23 | expect(result).hasNoFieldErrors('legalName'); 24 | }); 25 | 26 | it('is null it has a required error', () => { 27 | const result = companySyncValidationSuite({ legalName: null }); 28 | expect(result).hasExpectedFieldError('legalName', /required/); 29 | }) 30 | 31 | it('is empty it has a required error', () => { 32 | const result = companySyncValidationSuite({ legalName: '' }); 33 | expect(result).hasExpectedFieldError('legalName', /required/); 34 | }) 35 | 36 | it('is fewer than 3 chars it has the expected min length error', () => { 37 | const result = companySyncValidationSuite({ legalName: 'ab' }); 38 | expect(result).hasExpectedFieldError('legalName', /at least 3/); 39 | }) 40 | 41 | it('is more than 30 chars it has the expected max length error', () => { 42 | const result = companySyncValidationSuite({ legalName: ' 234567890 234567890 !TOO LONG!' }); 43 | expect(result).hasExpectedFieldError('legalName', /at most 30/); 44 | }) 45 | }); 46 | 47 | describe('when fein', () => { 48 | it('is well-formatted it passes', () => { 49 | const result = companySyncValidationSuite({ fein: '12-1234567' }); 50 | expect(result).hasNoFieldErrors('fein'); 51 | }); 52 | 53 | it('is missing the dash it has a format error', () => { 54 | const result = companySyncValidationSuite({ fein: '121234567' }); 55 | expect(result).hasExpectedFieldError('fein', /format/); 56 | }); 57 | 58 | it('is too short it has a format error', () => { 59 | const result = companySyncValidationSuite({ fein: '12-123456' }); 60 | expect(result).hasExpectedFieldError('fein', /format/); 61 | }); 62 | 63 | it('is too long it has a format error', () => { 64 | const result = companySyncValidationSuite({ fein: '12-12345678' }); 65 | expect(result).hasExpectedFieldError('fein', /format/); 66 | }); 67 | 68 | it('has alpha chars it has a format error', () => { 69 | const result = companySyncValidationSuite({ fein: '12-123A567' }); 70 | expect(result).hasExpectedFieldError('fein', /format/); 71 | }); 72 | 73 | it('is null it has a required error', () => { 74 | const result = companySyncValidationSuite({ fein: null }); 75 | expect(result).hasExpectedFieldError('fein', /required/); 76 | }) 77 | 78 | it('is empty it has a required error', () => { 79 | const result = companySyncValidationSuite({ fein: '' }); 80 | expect(result).hasExpectedFieldError('fein', /required/); 81 | }) 82 | }); 83 | 84 | describe('when work address', () => { 85 | // Leave most of the address testing to the addressSyncValidationSuite tests. 86 | // Test just enough to show that address validation is happening for the companySyncValidation suite. 87 | 88 | it('is valid, there are no work address errors', () => { 89 | const result = companySyncValidationSuite({ 90 | workAddress: { 91 | street: '123 Main', 92 | city: 'Somewhere', 93 | state: 'CA', 94 | postalCode: '94123' 95 | } as Address 96 | }); 97 | const hasAddressErrors = result.hasErrorsByGroup('workAddress'); 98 | expect(hasAddressErrors).toBeFalse(); 99 | }); 100 | 101 | it('is empty, it has errors', () => { 102 | const result = companySyncValidationSuite({}); 103 | const hasAddressErrors = result.hasErrorsByGroup('workAddress'); 104 | expect(hasAddressErrors).toBeTrue(); 105 | }); 106 | 107 | it('is incomplete, it has errors', () => { 108 | const result = companySyncValidationSuite({ 109 | workAddress: { 110 | street: '123 Main', 111 | city: 'Somewhere', 112 | // state: 'CA', 113 | // postalCode: '94123' 114 | } as Address 115 | }); 116 | const hasAddressErrors = result.hasErrorsByGroup('workAddress'); 117 | expect(hasAddressErrors).toBeTrue(); 118 | }); 119 | }); 120 | }); 121 | -------------------------------------------------------------------------------- /src/app/validators/company.sync-validations.ts: -------------------------------------------------------------------------------- 1 | import { create, enforce, group, omitWhen, only, test } from 'vest'; 2 | 3 | import { addressSyncValidations } from './address.sync-validations'; 4 | import { Company } from '@model'; 5 | import { isGoodFein } from '@services/fein-validation.service'; 6 | import { ValidationContext, ValidationSuite, ValidationSuiteFn } from '@validation'; 7 | 8 | /** Company Synchronous Validation Suite */ 9 | export const companySyncValidationSuite: ValidationSuite = create('CompanySyncValidationSuite', ( 10 | /** The object with data to validate */ 11 | model: Partial, 12 | /** The property of that data to validate, if we only want to validate one property */ 13 | field?: string, 14 | /** The group of properties in that data to validate, if we only want to validate one group */ 15 | groupName?: string, 16 | /** Extra resources that a validator might need */ 17 | context?: ValidationContext 18 | ) => { 19 | only(field); // if field defined, limit to tests of this field 20 | only.group(groupName); // if groupName defined, limit to tests of this group 21 | group('company', () => companySyncValidations(model, field, groupName, context)); 22 | group('workAddress', () => addressSyncValidations(model.workAddress!, field, groupName, context)); 23 | }); 24 | 25 | /** Company Synchronous Validations, written in vest. */ 26 | export const companySyncValidations: ValidationSuiteFn = (model: Partial) => { 27 | model = model ?? {}; 28 | 29 | test('legalName', 'Legal Name is required', () => { 30 | enforce(model.legalName).isNotBlank(); 31 | }); 32 | 33 | omitWhen(!model.legalName, () => { 34 | test('legalName', 'Legal Name must be at least 3 characters long', () => { 35 | enforce(model.legalName).longerThanOrEquals(3); 36 | }); 37 | 38 | test('legalName', 'Legal Name may be at most 30 characters long', () => { 39 | enforce(model.legalName).shorterThanOrEquals(30); 40 | }); 41 | }); 42 | 43 | test('fein', 'Tax Number is required', () => { 44 | enforce(model.fein).isNotBlank(); 45 | }); 46 | 47 | test('fein', 'Tax Number format must be 99-9999999', () => { 48 | enforce(isGoodFein(model.fein)).equals(true); 49 | }); 50 | } 51 | -------------------------------------------------------------------------------- /src/app/validators/employee.sync-validations.ts: -------------------------------------------------------------------------------- 1 | import { create, enforce, group, only, test } from 'vest'; 2 | 3 | import { addressSyncValidations } from './address.sync-validations'; 4 | import { Employee, EmployeeType } from '@model'; 5 | import { ValidationContext, ValidationSuite, ValidationSuiteFn } from '@validation'; 6 | 7 | const employeeTypes = [EmployeeType.Contractor, EmployeeType.FullTime, EmployeeType.PartTime]; 8 | 9 | 10 | /** Employee Synchronous Validation Suite */ 11 | export const employeeSyncValidationSuite: ValidationSuite = 12 | create('EmployeeSyncValidationSuite', 13 | (model: Partial, field?: string, groupName?: string, context?: ValidationContext) => { 14 | only(field); // if field defined, limit to tests of this field 15 | only.group(groupName); // if groupName defined, limit to tests of this group 16 | group('employee', () => employeeSyncValidations(model, field, groupName, context)); 17 | group('homeAddress', () => addressSyncValidations(model, field, groupName, context)); 18 | }); 19 | 20 | /** Employee Synchronous Validations, written in vest. */ 21 | export const employeeSyncValidations: ValidationSuiteFn = (model: Partial) => { 22 | model = model ?? {}; 23 | 24 | test('name', 'Employee name is required', () => { 25 | enforce(model.name).isNotBlank(); 26 | }); 27 | 28 | test('employeeType', 'Employee Type is required', () => { 29 | enforce(model.employeeType).isNotBlank(); 30 | }); 31 | 32 | test('employeeType', `Employee Type must be ${employeeTypes.join(' or ')}`, () => { 33 | enforce(model.employeeType).condition(type => employeeTypes.includes(type)); 34 | }); 35 | 36 | } 37 | -------------------------------------------------------------------------------- /src/app/validators/forbidden-validator.ts: -------------------------------------------------------------------------------- 1 | import { Directive, Input } from '@angular/core'; 2 | import { AbstractControl, NG_VALIDATORS, Validator, ValidationErrors, ValidatorFn } from '@angular/forms'; 3 | 4 | // Example custom validator 5 | // Borrowed from https://angular.io/guide/form-validation#defining-custom-validators 6 | 7 | /** A name can't match the given regular expression */ 8 | export function forbiddenNameValidator(nameRe: RegExp): ValidatorFn { 9 | return (control: AbstractControl): ValidationErrors | null => { 10 | const forbidden = nameRe.test(control.value); 11 | return forbidden ? {forbiddenName: `${control.value} is forbidden`} : null; 12 | }; 13 | } 14 | 15 | @Directive({ 16 | // eslint-disable-next-line @angular-eslint/directive-selector 17 | selector: '[forbiddenName]', 18 | standalone: true, 19 | providers: [{provide: NG_VALIDATORS, useExisting: ForbiddenValidatorDirective, multi: true}] 20 | }) 21 | export class ForbiddenValidatorDirective implements Validator { 22 | @Input() forbiddenName!: string; 23 | 24 | validate(control: AbstractControl): ValidationErrors | null { 25 | this.forbiddenName = this.forbiddenName || '^bob$'; // 'bob' is forbidden by default 26 | return this.forbiddenName 27 | ? forbiddenNameValidator(new RegExp(this.forbiddenName, 'i'))(control) 28 | : null; 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /src/app/validators/index.ts: -------------------------------------------------------------------------------- 1 | export * from './address.sync-validations'; 2 | export * from './app-validation-context'; 3 | export * from './company.async-validations'; 4 | export * from './company.sync-validations'; 5 | export * from './validation-suites'; 6 | -------------------------------------------------------------------------------- /src/app/validators/unit-test-validation-helpers.ts: -------------------------------------------------------------------------------- 1 | import { SuiteRunResult } from 'vest'; 2 | type FailureMessages = Record; 3 | 4 | import MatchersUtil = jasmine.MatchersUtil; 5 | import CustomMatcherFactories = jasmine.CustomMatcherFactories; 6 | import CustomMatcher = jasmine.CustomMatcher; 7 | import CustomMatcherResult = jasmine.CustomMatcherResult; 8 | 9 | import { AppValidationContext } from './app-validation-context'; 10 | import { FeinValidationService, FeinValidationResponse, isGoodFein } from '@services'; 11 | import { UsStates } from '@model'; 12 | 13 | export const disabledState = UsStates.find(s => s.disabled === false); 14 | export const supportedState = UsStates.find(s => s.name === 'California'); 15 | 16 | // TO MAKE TYPESCRIPT HAPPY, MUST ALSO REGISTER EACH CUSTOM MATCHER WITH unit-test-validation-matcher-types.d.ts 17 | /** Jasmine custom matchers that simplify vest validation testing. */ 18 | export const customVestSuiteResultMatchers: CustomMatcherFactories = { 19 | /** The validation result should have the expected error - determined by the RegExp - for the given field. 20 | * If there is no RegExp, then passes if the field has any error. 21 | */ 22 | hasExpectedFieldError: function (_util: MatchersUtil): CustomMatcher { 23 | return { 24 | compare: function hasExpectedFieldError(actual: SuiteRunResult, field: string, errRegExp?: RegExp): CustomMatcherResult { 25 | const errors = actual.getErrors()[field]; 26 | let message: string | undefined; 27 | if (errors) { 28 | if (errRegExp && !errors.some(e => errRegExp.test(e))) { 29 | message = `Expected one of the "${field}" errors to match ${errRegExp}; got ${JSON.stringify(errors)}`; 30 | } 31 | } else { 32 | message = `Expected errors for field "${field}" but got none`; 33 | } 34 | const pass = message == null; 35 | return { 36 | pass, 37 | message: pass ? `has expected error for "${field}"` : message 38 | }; 39 | } 40 | } 41 | }, 42 | 43 | /** The validation result should NOT have any errors for the given field. */ 44 | hasNoFieldErrors: function (_util: MatchersUtil): CustomMatcher { 45 | return { 46 | compare: function (actual: SuiteRunResult, field: string): CustomMatcherResult { 47 | const errors = actual.getErrors()[field]; 48 | let message: string | undefined; 49 | if (errors) { 50 | message = `Expected no errors for field "${field}" but got ${JSON.stringify(errors)}`; 51 | } 52 | const pass = message == null; 53 | // Result and message generation. 54 | return { 55 | pass, 56 | message: pass ? `"${field}" has no errors` : message 57 | }; 58 | } 59 | } 60 | } 61 | }; 62 | 63 | export class TestFeinValidationService { 64 | /** Check if an FEIN/Legal Name combination is valid 65 | * @returns Promise of the faked service response. 66 | */ 67 | check(fein: string): Promise { 68 | if (!isGoodFein(fein)) { 69 | return Promise.reject(`Bad FEIN "${fein}"`); 70 | } 71 | 72 | const lead = fein.substring(0, 2); // mock response based on lead 2 digits. 73 | if (fein === '13-1234567') { 74 | return Promise.resolve({ fein, feinName: 'MARVELOUS PRODUCTS, INC.'}); 75 | } else if (lead === '22') { 76 | return Promise.resolve({ fein, feinName: '*' }); // Always OK 77 | } else { 78 | return Promise.resolve({ fein }); // Always BAD 79 | } 80 | } 81 | } 82 | 83 | export const testAppContext: AppValidationContext = { 84 | feinValidationService: new TestFeinValidationService() as FeinValidationService, 85 | } 86 | -------------------------------------------------------------------------------- /src/app/validators/unit-test-validation-matcher-types.d.ts: -------------------------------------------------------------------------------- 1 | // import { SuiteRunResult } from 'vest'; 2 | 3 | declare namespace jasmine { 4 | interface Matchers { 5 | /** The validation result should have the expected error - determined by the RegExp - for the given field. 6 | * If there is no RegExp, then passes if the field has any error. 7 | */ 8 | hasExpectedFieldError(field: string, errRegExp?: RegExp, expectationFailOutput?: any): boolean; 9 | /** The validation result should NOT have any errors for the given field. */ 10 | hasNoFieldErrors(field: string, expectationFailOutput?: any): boolean; 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /src/app/validators/validation-suites.ts: -------------------------------------------------------------------------------- 1 | import { Provider } from '@angular/core'; 2 | 3 | import { addressSyncValidationSuite } from './address.sync-validations'; 4 | import { companySyncValidationSuite } from './company.sync-validations'; 5 | import { employeeSyncValidationSuite } from './employee.sync-validations'; 6 | import { createCompanyAsyncValidationSuite } from './company.async-validations'; 7 | 8 | import { extendVest } from './vest-enforce-extension'; 9 | extendVest(); 10 | 11 | import { Indexable } from '@utils'; 12 | import { ASYNC_VALIDATION_SUITE_FACTORIES, SYNC_VALIDATION_SUITES, ValidationSuite } from '@validation'; 13 | 14 | /** Synchronous Vest Validation Suites for this app, keyed by model type. */ 15 | export const syncValidationSuites: Indexable = { 16 | address: addressSyncValidationSuite, 17 | company: companySyncValidationSuite, 18 | employee: employeeSyncValidationSuite, 19 | }; 20 | 21 | /** Creators of Asynchronous Vest Validation Suites for this app, keyed by model type. 22 | * @see `form-field-ng-model-directive.ts` 23 | */ 24 | export const asyncValidationSuiteFactories: Indexable<() => ValidationSuite> = { 25 | company: createCompanyAsyncValidationSuite, 26 | }; 27 | 28 | /** Providers for the application-specific sync and async validation suite maps. */ 29 | export const validationSuiteProviders: Provider[] = [ 30 | { provide: ASYNC_VALIDATION_SUITE_FACTORIES, useValue: asyncValidationSuiteFactories }, 31 | { provide: SYNC_VALIDATION_SUITES, useValue: syncValidationSuites }, 32 | ]; 33 | -------------------------------------------------------------------------------- /src/app/validators/validator.d.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * Declare tree-shakable validators from the validator.js library 3 | * https://www.npmjs.com/package/validator 4 | */ 5 | declare module 'validator/es/lib/isEmail'; 6 | declare module 'validator/es/lib/isPostalCode'; 7 | -------------------------------------------------------------------------------- /src/app/validators/vest-enforce-extension.ts: -------------------------------------------------------------------------------- 1 | /** Extend vest.enforce with external validation rules from the validator.js library 2 | * https://vestjs.dev/docs/enforce/consuming_external_rules 3 | * To take effect, must export something that is used somewhere else. 4 | * In this example, that "something" is the `extendVest` function. 5 | * Can't just call it here because would be "optimized" away. 6 | */ 7 | import { enforce } from 'vest'; 8 | import isEmail from 'validator/es/lib/isEmail'; 9 | import isPostalCode from 'validator/es/lib/isPostalCode'; 10 | 11 | /** Extend vest's `enforce` function with external validation rules from the validator.js library. */ 12 | export function extendVest() { 13 | enforce.extend({ isEmail, isPostalCode }); 14 | } 15 | -------------------------------------------------------------------------------- /src/app/widgets/index.ts: -------------------------------------------------------------------------------- 1 | export * from './interfaces'; 2 | export * from './input-error.component'; 3 | export * from './input-select.component'; 4 | export * from './input-text.component'; 5 | -------------------------------------------------------------------------------- /src/app/widgets/input-base.component.ts: -------------------------------------------------------------------------------- 1 | import { Component, AfterViewInit, ElementRef, EventEmitter, HostBinding, Input, OnChanges, OnDestroy, OnInit, Optional, Output, ViewChild } from '@angular/core'; 2 | import { FormControl, NgModel, Validators } from '@angular/forms'; 3 | import { BooleanInput, coerceBooleanProperty } from '@angular/cdk/coercion'; 4 | import { Subscription } from 'rxjs'; 5 | 6 | import { Indexable } from '@core'; 7 | import { FormHooks, nameCounter, NgModelOptions, trim } from '@app/widgets/interfaces'; 8 | import { FormValidationScopeDirective, ValidationContext } from '@validation'; 9 | 10 | /** Base component for input element wrapper classes. Never instantiated! */ 11 | // Shouldn't have a Component decorator but Angular won't compile w/o it. 12 | @Component({ 13 | standalone: true, 14 | selector: 'app-input-base', 15 | template: '' 16 | }) 17 | export abstract class InputBaseComponent implements AfterViewInit, OnInit, OnChanges, OnDestroy { 18 | @HostBinding('class') protected get klass() { return this.className; } 19 | @Input() context?: ValidationContext; 20 | @Input() 21 | get disabled(): boolean { return this._disabled; }; 22 | set disabled(value: BooleanInput) { this._disabled = coerceBooleanProperty(value); } 23 | protected _disabled = false; 24 | 25 | @Input() field?: string; 26 | @Input() group?: string; 27 | @Input() label?: string; 28 | // eslint-disable-next-line @angular-eslint/no-input-rename 29 | @Input('model') inputModel?: Indexable; 30 | @Input() modelType?: string; 31 | @Input() name?: string; 32 | @Input() placeholder?: string; 33 | @Input() type = 'text'; 34 | @Input() updateOn?: FormHooks; 35 | 36 | /** Emit when the field value changes. */ 37 | @Output() changed = new EventEmitter(); 38 | 39 | @ViewChild('input') inputElRef?: ElementRef; 40 | @ViewChild('ngModel') ngModel?: NgModel; 41 | 42 | protected className: string; 43 | control?: FormControl; 44 | private hostEl: HTMLInputElement = this.hostElRef.nativeElement; 45 | model?: Indexable; 46 | protected ngModelOptions?: NgModelOptions; 47 | originalValue: any | null = null; 48 | scopeSub?: Subscription; 49 | 50 | get value() { 51 | return this.model![this.field!]; 52 | } 53 | 54 | set value(val: string) { 55 | // TODO: coerce value to type of original value 56 | val = trim(val); 57 | if (this.field) { 58 | this.model![this.field] = val; 59 | } 60 | this.changed.emit(val); 61 | } 62 | 63 | constructor( 64 | @Optional() protected formValidationScope: FormValidationScopeDirective, 65 | protected hostElRef: ElementRef 66 | ) { 67 | // Apply the class attribute on the host; if none, apply app standard CSS classes 68 | this.className = this.hostEl.className || "col full-width"; 69 | this.scopeSub = formValidationScope?.changed.subscribe(_ => this.ngOnChanges()) // might reset the model 70 | } 71 | 72 | ngOnChanges(): void { 73 | // only care about inputModel and updateOn changes; changes to other input vars are ignored. 74 | // inputModel trumps validation scope model 75 | this.model = this.inputModel ?? this.formValidationScope?.model ?? {}; 76 | if (this.updateOn) { 77 | this.ngModelOptions = { updateOn: this.updateOn }; 78 | } 79 | } 80 | 81 | ngOnInit(): void { 82 | this.field = this.field || this.name; 83 | this.name = this.name || `${(this.field ?? '')}$${nameCounter.next}`; 84 | this.originalValue = trim(this.model![this.field!]); 85 | } 86 | 87 | ngAfterViewInit() { 88 | this.control = this.ngModel!.control; 89 | if (this.hostEl.hasAttribute('required')) { 90 | // Pass it along to the nested input element 91 | // Wait a tick to bypass ExpressionChangedAfterItHasBeenCheckedError 92 | setTimeout(() => { 93 | // Adding the required validator triggers Angular Material 94 | // to add the required attribute and update the label with the required marker. 95 | this.control!.addValidators(Validators.required); 96 | this.control!.updateValueAndValidity({ onlySelf: true }); 97 | }); 98 | } 99 | } 100 | 101 | ngOnDestroy(): void { 102 | this.scopeSub?.unsubscribe(); 103 | } 104 | 105 | /** User pressed escape. Restores original value */ 106 | protected escaped() { 107 | const elementValue = this.inputElRef!.nativeElement.value; 108 | if (elementValue !== this.originalValue) { 109 | this.value = this.originalValue; 110 | } 111 | } 112 | } 113 | -------------------------------------------------------------------------------- /src/app/widgets/input-error.component.ts: -------------------------------------------------------------------------------- 1 | import { Component, Input, OnDestroy, OnInit } from '@angular/core'; 2 | import { CommonModule } from '@angular/common'; 3 | import { FormControl, ValidationErrors } from '@angular/forms'; 4 | import { Subscription } from 'rxjs'; 5 | 6 | @Component({ 7 | // eslint-disable-next-line @angular-eslint/component-selector 8 | selector: 'input-error', 9 | standalone: true, 10 | imports: [CommonModule], 11 | 12 | template: ` 13 |
14 | {{ error }} 15 | validating... 16 |
17 | `, 18 | }) 19 | export class InputErrorComponent implements OnDestroy, OnInit { 20 | @Input() control?: Partial 21 | 22 | error?: ValidationErrors | null; 23 | pending = false; 24 | 25 | private sub?: Subscription; 26 | get show() { 27 | return !!this.control?.touched; 28 | } 29 | 30 | ngOnInit(): void { 31 | if (this.control) { 32 | const control = this.control; 33 | this.sub = control.statusChanges!.subscribe(changes => { 34 | this.error = null; 35 | this.pending = false; 36 | if (changes === 'INVALID') { 37 | this.error = control.errors ? control.errors!['error'] : null; 38 | } else { 39 | this.pending = changes ==='PENDING'; 40 | } 41 | }); 42 | } 43 | } 44 | 45 | ngOnDestroy(): void { 46 | this.sub?.unsubscribe(); 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /src/app/widgets/input-select.component.ts: -------------------------------------------------------------------------------- 1 | import { Component, ElementRef, Input, Optional } from '@angular/core'; 2 | import { CommonModule } from '@angular/common'; 3 | import { FormsModule } from '@angular/forms'; 4 | import { MatInputModule } from '@angular/material/input'; 5 | 6 | import { formContainerViewProvider } from '@core'; 7 | import { FormFieldNgModelDirective } from '@validation/form-field-ng-model.directive'; 8 | import { FormValidationScopeDirective } from '@validation'; 9 | import { InputBaseComponent } from './input-base.component'; 10 | import { InputErrorComponent } from './input-error.component'; 11 | import { SelectOption } from './interfaces'; 12 | 13 | @Component({ 14 | // eslint-disable-next-line @angular-eslint/component-selector 15 | selector: 'input-select', 16 | standalone: true, 17 | imports: [CommonModule, FormsModule, InputErrorComponent, MatInputModule, FormFieldNgModelDirective], 18 | viewProviders: [formContainerViewProvider], 19 | 20 | template: ` 21 | 22 | {{label}} 23 | 39 | 40 | 41 | `, 42 | }) 43 | export class InputSelectComponent extends InputBaseComponent { 44 | @Input() options: SelectOption[] = []; 45 | 46 | /** Display this text as the (disabled) first option when the model.field is "empty" or not among the choices. */ 47 | @Input() placeholderOption = ''; 48 | 49 | constructor( 50 | @Optional() formValidationScope: FormValidationScopeDirective, 51 | hostElRef: ElementRef 52 | ) { 53 | super(formValidationScope, hostElRef); 54 | } 55 | 56 | get showPlaceholderOption() { 57 | return this.placeholderOption && (this.value === '' || this.value == null || this.options.every(opt => opt.value !== this.value)); 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /src/app/widgets/input-text.component.ts: -------------------------------------------------------------------------------- 1 | import { Component, ElementRef, Optional } from '@angular/core'; 2 | import { CommonModule } from '@angular/common'; 3 | import { FormsModule } from '@angular/forms'; 4 | import { MatInputModule } from '@angular/material/input'; 5 | 6 | import { formContainerViewProvider } from '@core'; 7 | import { FormFieldNgModelDirective } from '@validation/form-field-ng-model.directive'; 8 | import { FormValidationScopeDirective } from '@validation'; 9 | import { InputBaseComponent } from './input-base.component'; 10 | import { InputErrorComponent } from './input-error.component'; 11 | 12 | @Component({ 13 | // eslint-disable-next-line @angular-eslint/component-selector 14 | selector: 'input-text', 15 | standalone: true, 16 | imports: [CommonModule, FormFieldNgModelDirective, FormsModule, InputErrorComponent, MatInputModule], 17 | viewProviders: [formContainerViewProvider], 18 | 19 | template: ` 20 | 21 | {{label}} 22 | 34 | 35 | 36 | `, 37 | }) 38 | export class InputTextComponent extends InputBaseComponent { 39 | constructor( 40 | @Optional() formValidationScope: FormValidationScopeDirective, 41 | hostElRef: ElementRef 42 | ) { 43 | super(formValidationScope, hostElRef) 44 | } 45 | 46 | protected onBlur() { 47 | this.trimControlValue(); 48 | } 49 | 50 | /** Trim the value in the ngModel control, which updates the screen and the value of the field in the parent form. */ 51 | private trimControlValue() { 52 | if (this.ngModel?.control.value !== this.value) { 53 | this.ngModel?.control.setValue(this.value, { emitEvent: false }); 54 | } 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /src/app/widgets/interfaces.ts: -------------------------------------------------------------------------------- 1 | import { Indexable } from '@utils'; 2 | 3 | /** Angular type for ngModelOptions.updateOn which is not exposed publicly. 4 | * @see https://github.com/angular/angular/blob/14.0.1/packages/forms/src/model/abstract_model.ts#L108 5 | */ 6 | export type FormHooks = 'change' | 'blur' | 'submit'; 7 | 8 | /** Angular type for ngModelOptions which is not exposed publicly. 9 | * @see https://github.com/angular/angular/blob/14.0.1/packages/forms/src/directives/ng_model.ts#L181-L198 10 | */ 11 | export interface NgModelOptions { 12 | name?: string; 13 | standalone?: boolean; 14 | updateOn?: FormHooks; 15 | } 16 | 17 | class NameCounter { 18 | counter = 0; 19 | get next() { return this.counter++; }; 20 | } 21 | export const nameCounter = new NameCounter(); 22 | 23 | /** Interface for options passed to the widget. */ 24 | export interface SelectOption { 25 | name: string; 26 | value: any; 27 | disabled?: boolean 28 | } 29 | 30 | /** Convert an indexable source into an array of SelectOptions for . */ 31 | export function toSelectOptions( 32 | source: Indexable[] | null | undefined, 33 | /** Source property to be mapped to `name`. */ 34 | nameProp = 'name', 35 | /** Source property to be mapped to `value`. */ 36 | valueProp = 'value', 37 | /** Source property indicating if option is disabled (false by default). */ 38 | disabledProp = 'disabled' 39 | ): SelectOption[] { 40 | return (source ?? []).map(opt => 41 | ({ 42 | name: opt[nameProp], 43 | value: opt[valueProp], 44 | disabled: opt[disabledProp] === true 45 | })); 46 | } 47 | 48 | /** Trim value if string. */ 49 | export function trim(value: any | null) { 50 | return typeof value === 'string' ? value.trim() : value; 51 | } 52 | -------------------------------------------------------------------------------- /src/assets/.gitkeep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wardbell/ngc-validate/9d4d5bd89c1b37f596a1722eec28c3001e6ba7e5/src/assets/.gitkeep -------------------------------------------------------------------------------- /src/assets/images/green-spinner-on-white.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wardbell/ngc-validate/9d4d5bd89c1b37f596a1722eec28c3001e6ba7e5/src/assets/images/green-spinner-on-white.gif -------------------------------------------------------------------------------- /src/environments/environment.prod.ts: -------------------------------------------------------------------------------- 1 | export const environment = { 2 | production: true 3 | }; 4 | -------------------------------------------------------------------------------- /src/environments/environment.ts: -------------------------------------------------------------------------------- 1 | // This file can be replaced during build by using the `fileReplacements` array. 2 | // `ng build` replaces `environment.ts` with `environment.prod.ts`. 3 | // The list of file replacements can be found in `angular.json`. 4 | 5 | export const environment = { 6 | production: false 7 | }; 8 | 9 | /* 10 | * For easier debugging in development mode, you can import the following file 11 | * to ignore zone related error stack frames such as `zone.run`, `zoneDelegate.invokeTask`. 12 | * 13 | * This import should be commented out in production mode because it will have a negative impact 14 | * on performance if an error is thrown. 15 | */ 16 | // import 'zone.js/plugins/zone-error'; // Included with Angular CLI. 17 | -------------------------------------------------------------------------------- /src/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wardbell/ngc-validate/9d4d5bd89c1b37f596a1722eec28c3001e6ba7e5/src/favicon.ico -------------------------------------------------------------------------------- /src/global.d.ts: -------------------------------------------------------------------------------- 1 | /** Typescript declarations for custom vest validation rules 2 | * https://vestjs.dev/docs/enforce/creating_custom_rules 3 | */ 4 | declare global { 5 | namespace n4s { 6 | interface EnforceCustomMatchers { 7 | // Don't mention the first, `value` arg 8 | isEmail(options?: any): R; 9 | isPostalCode(locale: string): R; 10 | } 11 | } 12 | } 13 | 14 | export {}; 15 | -------------------------------------------------------------------------------- /src/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | NGC Validate 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | -------------------------------------------------------------------------------- /src/main.ts: -------------------------------------------------------------------------------- 1 | import { enableProdMode, ENVIRONMENT_INITIALIZER, inject, importProvidersFrom } from '@angular/core'; 2 | import { bootstrapApplication } from '@angular/platform-browser'; 3 | import { HttpClientModule } from '@angular/common/http' 4 | import { RouterModule } from '@angular/router'; 5 | 6 | import { AppComponent } from '@app/app.component'; 7 | import { appRoutes } from '@app/app.routes'; 8 | import { environment } from '@environment'; 9 | import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; 10 | 11 | import { DataService, RemoteDataService } from '@services'; 12 | 13 | import { appValidationContextProvider, validationSuiteProviders } from '@validators'; 14 | 15 | if (environment.production) { 16 | enableProdMode(); 17 | } 18 | 19 | bootstrapApplication(AppComponent, { 20 | providers: [ 21 | importProvidersFrom(BrowserAnimationsModule, HttpClientModule), 22 | importProvidersFrom(RouterModule.forRoot(appRoutes)), 23 | appValidationContextProvider, 24 | validationSuiteProviders, 25 | { 26 | provide: ENVIRONMENT_INITIALIZER, 27 | multi: true, 28 | useValue() { 29 | inject(RemoteDataService).init(); 30 | inject(DataService).init(); 31 | } 32 | } 33 | ] 34 | }).catch(err => console.error(err)); 35 | -------------------------------------------------------------------------------- /src/polyfills.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * This file includes polyfills needed by Angular and is loaded before the app. 3 | * You can add your own extra polyfills to this file. 4 | * 5 | * This file is divided into 2 sections: 6 | * 1. Browser polyfills. These are applied before loading ZoneJS and are sorted by browsers. 7 | * 2. Application imports. Files imported after ZoneJS that should be loaded before your main 8 | * file. 9 | * 10 | * The current setup is for so-called "evergreen" browsers; the last versions of browsers that 11 | * automatically update themselves. This includes recent versions of Safari, Chrome (including 12 | * Opera), Edge on the desktop, and iOS and Chrome on mobile. 13 | * 14 | * Learn more in https://angular.io/guide/browser-support 15 | */ 16 | 17 | /*************************************************************************************************** 18 | * BROWSER POLYFILLS 19 | */ 20 | 21 | /** 22 | * By default, zone.js will patch all possible macroTask and DomEvents 23 | * user can disable parts of macroTask/DomEvents patch by setting following flags 24 | * because those flags need to be set before `zone.js` being loaded, and webpack 25 | * will put import in the top of bundle, so user need to create a separate file 26 | * in this directory (for example: zone-flags.ts), and put the following flags 27 | * into that file, and then add the following code before importing zone.js. 28 | * import './zone-flags'; 29 | * 30 | * The flags allowed in zone-flags.ts are listed here. 31 | * 32 | * The following flags will work for all browsers. 33 | * 34 | * (window as any).__Zone_disable_requestAnimationFrame = true; // disable patch requestAnimationFrame 35 | * (window as any).__Zone_disable_on_property = true; // disable patch onProperty such as onclick 36 | * (window as any).__zone_symbol__UNPATCHED_EVENTS = ['scroll', 'mousemove']; // disable patch specified eventNames 37 | * 38 | * in IE/Edge developer tools, the addEventListener will also be wrapped by zone.js 39 | * with the following flag, it will bypass `zone.js` patch for IE/Edge 40 | * 41 | * (window as any).__Zone_enable_cross_context_check = true; 42 | * 43 | */ 44 | 45 | /*************************************************************************************************** 46 | * Zone JS is required by default for Angular itself. 47 | */ 48 | import 'zone.js'; // Included with Angular CLI. 49 | 50 | 51 | /*************************************************************************************************** 52 | * APPLICATION IMPORTS 53 | */ 54 | -------------------------------------------------------------------------------- /src/styles.scss: -------------------------------------------------------------------------------- 1 | @use '@angular/material' as mat; 2 | @include mat.core(); 3 | 4 | // Light theme 5 | $light-primary: mat.define-palette(mat.$indigo-palette); 6 | $light-accent: mat.define-palette(mat.$pink-palette); 7 | $light-theme: mat.define-light-theme(( 8 | color: ( 9 | primary: $light-primary, 10 | accent: $light-accent, 11 | ) 12 | )); 13 | 14 | // Apply the light theme by default 15 | @include mat.core-theme($light-theme); 16 | @include mat.button-theme($light-theme); 17 | 18 | html, body { height: 100%; } 19 | body { 20 | font-family: Roboto, "Helvetica Neue", sans-serif; 21 | font-size: 12px; 22 | margin: 0.5rem; 23 | } 24 | 25 | // Hide the spinner when the input type is 'number'. The spinner is a bad joke. 26 | input[type=number]::-webkit-inner-spin-button, input[type=number]::-webkit-outer-spin-button { 27 | -webkit-appearance: none; 28 | margin: 0; 29 | } 30 | 31 | .row { 32 | display: flex; 33 | flex-direction: row; 34 | } 35 | 36 | .col { 37 | flex: 1; 38 | margin-right: 20px; 39 | } 40 | 41 | .col:last-child { 42 | margin-right: 0; 43 | } 44 | 45 | 46 | .full-width { 47 | width: 100%; 48 | } 49 | 50 | .short-width { 51 | min-width: 5rem; 52 | width: 22%; 53 | } 54 | 55 | .mid-width { 56 | min-width: 5rem; 57 | max-width: 20rem; 58 | width: 50%; 59 | } 60 | 61 | mat-card { 62 | margin: 1rem auto; 63 | max-width: 100rem; 64 | min-width: 10rem; 65 | width: 95%; 66 | } 67 | 68 | mat-card-header { 69 | margin-left: -16px; 70 | margin-bottom: 1rem; 71 | } 72 | 73 | .mat-radio-button { 74 | display: block; 75 | margin: 5px 0; 76 | } 77 | 78 | @keyframes blink { 79 | 50% { 80 | opacity: 0.0; 81 | } 82 | } 83 | 84 | input-error { 85 | .error { 86 | color: red; 87 | font-size: 80% 88 | } 89 | .pending { 90 | animation: blink 1s step-start 0s infinite; 91 | color: blue; 92 | font-size: 80% 93 | } 94 | } 95 | -------------------------------------------------------------------------------- /src/test.ts: -------------------------------------------------------------------------------- 1 | // This file is required by karma.conf.js and loads recursively all the .spec and framework files 2 | 3 | import 'zone.js/testing'; 4 | import { getTestBed } from '@angular/core/testing'; 5 | import { 6 | BrowserDynamicTestingModule, 7 | platformBrowserDynamicTesting 8 | } from '@angular/platform-browser-dynamic/testing'; 9 | 10 | declare const require: { 11 | context(path: string, deep?: boolean, filter?: RegExp): { 12 | (id: string): T; 13 | keys(): string[]; 14 | }; 15 | }; 16 | 17 | // First, initialize the Angular testing environment. 18 | getTestBed().initTestEnvironment( 19 | BrowserDynamicTestingModule, 20 | platformBrowserDynamicTesting(), 21 | ); 22 | 23 | // Then we find all the tests. 24 | const context = require.context('./', true, /\.spec\.ts$/); 25 | // And load the modules. 26 | context.keys().forEach(context); 27 | -------------------------------------------------------------------------------- /tsconfig.app.json: -------------------------------------------------------------------------------- 1 | /* To learn more about this file see: https://angular.io/config/tsconfig. */ 2 | { 3 | "extends": "./tsconfig.json", 4 | "compilerOptions": { 5 | "outDir": "./out-tsc/app", 6 | "types": [] 7 | }, 8 | "files": [ 9 | "src/main.ts", 10 | "src/polyfills.ts" 11 | ], 12 | "include": [ 13 | "src/**/*.d.ts" 14 | ] 15 | } 16 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | /* To learn more about this file see: https://angular.io/config/tsconfig. */ 2 | { 3 | "compileOnSave": false, 4 | "compilerOptions": { 5 | "paths": { 6 | "@app/*": ["src/app/*"], 7 | "@core": ["src/app/core/index"], 8 | "@core/*": ["src/app/core/*"], 9 | "@environment": ["src/environments/environment"], 10 | "@imports": ["src/app/core/imports.ts"], 11 | "@model": ["src/app/model/index"], 12 | "@model/*": ["src/app/model/*"], 13 | "@services": ["src/app/services/index"], 14 | "@services/*": ["src/app/services/*"], 15 | "@shared": ["src/app/shared/index"], 16 | "@shared/*": ["src/app/shared/*"], 17 | "@utils": ["src/app/core/utils/index"], 18 | "@utils/*": ["src/app/core/utils/*"], 19 | "@validation": ["src/app/validation/index"], 20 | "@validation/*": ["src/app/validation/*"], 21 | "@validators": ["src/app/validators/index"], 22 | "@validators/*": ["src/app/validators/*"], 23 | }, 24 | "baseUrl": "./", 25 | "outDir": "./dist/out-tsc", 26 | "forceConsistentCasingInFileNames": true, 27 | "strict": true, 28 | "noImplicitOverride": true, 29 | "noPropertyAccessFromIndexSignature": true, 30 | "noImplicitReturns": true, 31 | "noFallthroughCasesInSwitch": true, 32 | "sourceMap": true, 33 | "declaration": false, 34 | "downlevelIteration": true, 35 | "experimentalDecorators": true, 36 | "moduleResolution": "node", 37 | "importHelpers": true, 38 | "target": "es2020", 39 | "module": "es2020", 40 | "lib": [ 41 | "es2020", 42 | "dom" 43 | ] 44 | }, 45 | "angularCompilerOptions": { 46 | "enableI18nLegacyMessageIdFormat": false, 47 | "preserveWhitespaces": false, 48 | "strictInjectionParameters": true, 49 | "strictInputAccessModifiers": true, 50 | "strictTemplates": true 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /tsconfig.spec.json: -------------------------------------------------------------------------------- 1 | /* To learn more about this file see: https://angular.io/config/tsconfig. */ 2 | { 3 | "extends": "./tsconfig.json", 4 | "compilerOptions": { 5 | "outDir": "./out-tsc/spec", 6 | "types": [ 7 | "jasmine" 8 | ] 9 | }, 10 | "files": [ 11 | "src/test.ts", 12 | "src/polyfills.ts" 13 | ], 14 | "include": [ 15 | "src/**/*.spec.ts", 16 | "src/**/*.d.ts" 17 | ] 18 | } 19 | --------------------------------------------------------------------------------