├── src ├── assets │ └── .gitkeep ├── app │ ├── app.component.scss │ ├── interface │ │ ├── validator.interface.ts │ │ └── control-config.interface.ts │ ├── components │ │ ├── button │ │ │ ├── button.component.html │ │ │ └── button.component.ts │ │ ├── dynamic-form │ │ │ ├── dynamic-form.component.html │ │ │ └── dynamic-form.component.ts │ │ ├── input │ │ │ ├── input.component.ts │ │ │ └── input.component.html │ │ ├── select │ │ │ ├── select.component.ts │ │ │ └── select.component.html │ │ └── dynamic-field │ │ │ └── dynamic-field.directive.ts │ ├── app.component.html │ ├── app.module.ts │ ├── app.component.ts │ └── data │ │ └── form-config.ts ├── favicon.ico ├── environments │ ├── environment.prod.ts │ └── environment.ts ├── styles.scss ├── tsconfig.app.json ├── tsconfig.spec.json ├── tslint.json ├── main.ts ├── browserslist ├── index.html ├── test.ts ├── karma.conf.js └── polyfills.ts ├── scripts ├── publish-page.sh └── publish.sh ├── projects └── ngx-validate │ ├── package.json │ ├── ng-package.json │ ├── ng-package.prod.json │ ├── src │ ├── public_api.ts │ ├── lib │ │ ├── ngx-validators.spec.ts │ │ ├── ngx-validate.module.ts │ │ ├── validation-error │ │ │ ├── validation-error.component.ts │ │ │ └── validation-error.component.html │ │ ├── ngx-validate.service.ts │ │ ├── utils │ │ │ └── util.ts │ │ └── ngx-validators.ts │ └── test.ts │ ├── tslint.json │ ├── tsconfig.spec.json │ ├── tsconfig.lib.json │ ├── karma.conf.js │ └── README.md ├── e2e ├── src │ ├── app.po.ts │ └── app.e2e-spec.ts ├── tsconfig.e2e.json └── protractor.conf.js ├── .editorconfig ├── tsconfig.json ├── .gitignore ├── package.json ├── tslint.json ├── angular.json └── README.md /src/assets/.gitkeep: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /src/app/app.component.scss: -------------------------------------------------------------------------------- 1 | .bg-danger{ 2 | background-color: #FF0000; 3 | } 4 | -------------------------------------------------------------------------------- /src/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/EdenWoo/ngx-validate/HEAD/src/favicon.ico -------------------------------------------------------------------------------- /src/environments/environment.prod.ts: -------------------------------------------------------------------------------- 1 | export const environment = { 2 | production: true 3 | }; 4 | -------------------------------------------------------------------------------- /src/styles.scss: -------------------------------------------------------------------------------- 1 | /* You can add global styles to this file, and also import other style files */ 2 | -------------------------------------------------------------------------------- /src/app/interface/validator.interface.ts: -------------------------------------------------------------------------------- 1 | export interface Validator { 2 | name: string; 3 | validator: any; 4 | message: string; 5 | } 6 | -------------------------------------------------------------------------------- /src/app/components/button/button.component.html: -------------------------------------------------------------------------------- 1 |
2 | 3 |
4 | -------------------------------------------------------------------------------- /scripts/publish-page.sh: -------------------------------------------------------------------------------- 1 | 2 | #!/usr/bin/env bash 3 | 4 | ng build --prod --base-href "https://github.io/EdenWoo/ngx-validate/" 5 | 6 | sudo ngh --dir dist/ngx-validate-lib --no-silent 7 | -------------------------------------------------------------------------------- /projects/ngx-validate/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "ngx-validate", 3 | "version": "0.0.21", 4 | "peerDependencies": { 5 | "@angular/common": "^7.1.0", 6 | "@angular/core": "^7.1.0" 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /projects/ngx-validate/ng-package.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "../../node_modules/ng-packagr/ng-package.schema.json", 3 | "dest": "../../dist/ngx-validate", 4 | "lib": { 5 | "entryFile": "src/public_api.ts" 6 | } 7 | } -------------------------------------------------------------------------------- /projects/ngx-validate/ng-package.prod.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "../../node_modules/ng-packagr/ng-package.schema.json", 3 | "dest": "../../dist/ngx-validate", 4 | "lib": { 5 | "entryFile": "src/public_api.ts" 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /src/tsconfig.app.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "../tsconfig.json", 3 | "compilerOptions": { 4 | "outDir": "../out-tsc/app", 5 | "types": [] 6 | }, 7 | "exclude": [ 8 | "test.ts", 9 | "**/*.spec.ts" 10 | ] 11 | } 12 | -------------------------------------------------------------------------------- /src/app/components/dynamic-form/dynamic-form.component.html: -------------------------------------------------------------------------------- 1 |
2 | 3 | 4 |
5 | -------------------------------------------------------------------------------- /e2e/src/app.po.ts: -------------------------------------------------------------------------------- 1 | import { browser, by, element } from 'protractor'; 2 | 3 | export class AppPage { 4 | navigateTo() { 5 | return browser.get('/'); 6 | } 7 | 8 | getTitleText() { 9 | return element(by.css('app-root h1')).getText(); 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /e2e/tsconfig.e2e.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "../tsconfig.json", 3 | "compilerOptions": { 4 | "outDir": "../out-tsc/app", 5 | "module": "commonjs", 6 | "target": "es5", 7 | "types": [ 8 | "jasmine", 9 | "jasminewd2", 10 | "node" 11 | ] 12 | } 13 | } -------------------------------------------------------------------------------- /projects/ngx-validate/src/public_api.ts: -------------------------------------------------------------------------------- 1 | /* 2 | * Public API Surface of ngx-validate 3 | */ 4 | 5 | export * from './lib/ngx-validate.service'; 6 | export * from './lib/validation-error/validation-error.component'; 7 | export * from './lib/ngx-validate.module'; 8 | export * from './lib/ngx-validators'; 9 | -------------------------------------------------------------------------------- /.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 | [*.md] 12 | max_line_length = off 13 | trim_trailing_whitespace = false 14 | -------------------------------------------------------------------------------- /scripts/publish.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | cd projects/ngx-validate 4 | 5 | npm --no-git-tag-version version patch 6 | 7 | ng build ngx-validate --prod 8 | 9 | cd ../../dist/ngx-validate 10 | 11 | npm publish 12 | 13 | cd ../../ 14 | 15 | git add . 16 | 17 | git commit -m "new version published" 18 | 19 | git push 20 | -------------------------------------------------------------------------------- /src/app/interface/control-config.interface.ts: -------------------------------------------------------------------------------- 1 | import {Validator} from './validator.interface'; 2 | 3 | export interface ControlConfig { 4 | label?: string; 5 | name?: string; 6 | inputType?: string; 7 | options?: string[]; 8 | collections?: any; 9 | type: string; 10 | value?: any; 11 | validations?: Validator[]; 12 | } 13 | -------------------------------------------------------------------------------- /projects/ngx-validate/tslint.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "../../tslint.json", 3 | "rules": { 4 | "directive-selector": [ 5 | true, 6 | "attribute", 7 | "lib", 8 | "camelCase" 9 | ], 10 | "component-selector": [ 11 | true, 12 | "element", 13 | "lib", 14 | "kebab-case" 15 | ] 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /projects/ngx-validate/tsconfig.spec.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "../../tsconfig.json", 3 | "compilerOptions": { 4 | "outDir": "../../out-tsc/spec", 5 | "types": [ 6 | "jasmine", 7 | "node" 8 | ] 9 | }, 10 | "files": [ 11 | "src/test.ts" 12 | ], 13 | "include": [ 14 | "**/*.spec.ts", 15 | "**/*.d.ts" 16 | ] 17 | } 18 | -------------------------------------------------------------------------------- /src/tsconfig.spec.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "../tsconfig.json", 3 | "compilerOptions": { 4 | "outDir": "../out-tsc/spec", 5 | "types": [ 6 | "jasmine", 7 | "node" 8 | ] 9 | }, 10 | "files": [ 11 | "test.ts", 12 | "polyfills.ts" 13 | ], 14 | "include": [ 15 | "**/*.spec.ts", 16 | "**/*.d.ts" 17 | ] 18 | } 19 | -------------------------------------------------------------------------------- /e2e/src/app.e2e-spec.ts: -------------------------------------------------------------------------------- 1 | import { AppPage } from './app.po'; 2 | 3 | describe('workspace-project App', () => { 4 | let page: AppPage; 5 | 6 | beforeEach(() => { 7 | page = new AppPage(); 8 | }); 9 | 10 | it('should display welcome message', () => { 11 | page.navigateTo(); 12 | expect(page.getTitleText()).toEqual('Welcome to ngx-validate-lib!'); 13 | }); 14 | }); 15 | -------------------------------------------------------------------------------- /src/tslint.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "../tslint.json", 3 | "rules": { 4 | "directive-selector": [ 5 | true, 6 | "attribute", 7 | "app", 8 | "camelCase" 9 | ], 10 | "component-selector": [ 11 | true, 12 | "element", 13 | "app", 14 | "kebab-case" 15 | ] 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /src/main.ts: -------------------------------------------------------------------------------- 1 | import { enableProdMode } from '@angular/core'; 2 | import { platformBrowserDynamic } from '@angular/platform-browser-dynamic'; 3 | 4 | import { AppModule } from './app/app.module'; 5 | import { environment } from './environments/environment'; 6 | 7 | if (environment.production) { 8 | enableProdMode(); 9 | } 10 | 11 | platformBrowserDynamic().bootstrapModule(AppModule) 12 | .catch(err => console.error(err)); 13 | -------------------------------------------------------------------------------- /src/browserslist: -------------------------------------------------------------------------------- 1 | # This file is currently used by autoprefixer to adjust CSS to support the below specified browsers 2 | # For additional information regarding the format and rule options, please see: 3 | # https://github.com/browserslist/browserslist#queries 4 | # 5 | # For IE 9-11 support, please remove 'not' from the last line of the file and adjust as needed 6 | 7 | > 0.5% 8 | last 2 versions 9 | Firefox ESR 10 | not dead 11 | not IE 9-11 -------------------------------------------------------------------------------- /src/app/app.component.html: -------------------------------------------------------------------------------- 1 | 2 |
3 |
4 |
5 |
6 |

Angular Reactive Form with NgxValidate

7 | 8 |
9 | {{ form.value | json }} 10 |
11 |
12 |
13 |
14 |
15 | -------------------------------------------------------------------------------- /src/app/components/input/input.component.ts: -------------------------------------------------------------------------------- 1 | import { Component, OnInit } from '@angular/core'; 2 | import { FormGroup } from '@angular/forms'; 3 | import {ControlConfig} from '../../interface/control-config.interface'; 4 | @Component({ 5 | selector: "app-input", 6 | templateUrl: './input.component.html', 7 | styles: [] 8 | }) 9 | export class InputComponent implements OnInit { 10 | field: ControlConfig; 11 | group: FormGroup; 12 | constructor() {} 13 | ngOnInit() {} 14 | } 15 | -------------------------------------------------------------------------------- /src/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | NgxValidate Example 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | -------------------------------------------------------------------------------- /src/app/components/button/button.component.ts: -------------------------------------------------------------------------------- 1 | import {Component, OnInit} from '@angular/core'; 2 | import {FormGroup} from '@angular/forms'; 3 | import {ControlConfig} from '../../interface/control-config.interface'; 4 | 5 | @Component({ 6 | selector: 'app-button', 7 | templateUrl: './button.component.html', 8 | styles: [] 9 | }) 10 | export class ButtonComponent implements OnInit { 11 | field: ControlConfig; 12 | group: FormGroup; 13 | 14 | constructor() { 15 | } 16 | 17 | ngOnInit() { 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /src/app/components/select/select.component.ts: -------------------------------------------------------------------------------- 1 | import {Component, OnInit} from '@angular/core'; 2 | import {FormGroup} from '@angular/forms'; 3 | import {ControlConfig} from '../../interface/control-config.interface'; 4 | 5 | @Component({ 6 | selector: 'app-select', 7 | templateUrl: './select.component.html', 8 | styles: [] 9 | }) 10 | export class SelectComponent implements OnInit { 11 | field: ControlConfig; 12 | group: FormGroup; 13 | 14 | constructor() { 15 | } 16 | 17 | ngOnInit() { 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /projects/ngx-validate/src/lib/ngx-validators.spec.ts: -------------------------------------------------------------------------------- 1 | import {FormControl} from '@angular/forms'; 2 | import {NgxValidators} from './ngx-validators'; 3 | 4 | describe('ngx validators service', () => { 5 | 6 | describe('isNumber', () => { 7 | it('when a input is not a number or +-., should return undefined', () => { 8 | const control: FormControl = new FormControl('wek'); 9 | const validated = NgxValidators.isNumber(control); 10 | expect(validated).toBeUndefined(); 11 | }); 12 | }); 13 | 14 | }); 15 | 16 | -------------------------------------------------------------------------------- /projects/ngx-validate/src/lib/ngx-validate.module.ts: -------------------------------------------------------------------------------- 1 | import {NgModule} from '@angular/core'; 2 | import {ValidationErrorComponent} from './validation-error/validation-error.component'; 3 | import {CommonModule} from '@angular/common'; 4 | import {FormsModule} from '@angular/forms'; 5 | 6 | @NgModule({ 7 | declarations: [ 8 | ValidationErrorComponent, 9 | ], 10 | imports: [ 11 | CommonModule, 12 | FormsModule], 13 | exports: [ 14 | ValidationErrorComponent 15 | ] 16 | }) 17 | export class NgxValidateModule { 18 | } 19 | -------------------------------------------------------------------------------- /src/app/components/input/input.component.html: -------------------------------------------------------------------------------- 1 |
2 | 3 | 8 | 9 | {{validation.message}} 10 | 11 |
12 | -------------------------------------------------------------------------------- /projects/ngx-validate/src/lib/validation-error/validation-error.component.ts: -------------------------------------------------------------------------------- 1 | import {Component, Input, OnInit} from '@angular/core'; 2 | import {AbstractControl, FormControl} from '@angular/forms'; 3 | 4 | @Component({ 5 | selector: 'validation-error', 6 | templateUrl: 'validation-error.component.html' 7 | }) 8 | export class ValidationErrorComponent implements OnInit { 9 | 10 | @Input() control: AbstractControl; 11 | @Input() errorClass: string; 12 | 13 | constructor() { 14 | 15 | } 16 | 17 | ngOnInit(): void { 18 | if (!this.control) { 19 | this.control = new FormControl(); 20 | } 21 | } 22 | } 23 | 24 | 25 | -------------------------------------------------------------------------------- /src/app/components/select/select.component.html: -------------------------------------------------------------------------------- 1 |
2 | 3 | 8 | 9 | {{validation.message}} 11 | 12 |
13 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compileOnSave": false, 3 | "compilerOptions": { 4 | "baseUrl": "./", 5 | "outDir": "./dist/out-tsc", 6 | "sourceMap": true, 7 | "declaration": false, 8 | "module": "es2015", 9 | "moduleResolution": "node", 10 | "emitDecoratorMetadata": true, 11 | "experimentalDecorators": true, 12 | "importHelpers": true, 13 | "target": "es5", 14 | "typeRoots": [ 15 | "node_modules/@types" 16 | ], 17 | "lib": [ 18 | "es2018", 19 | "dom" 20 | ], 21 | "paths": { 22 | "ngx-validate": [ 23 | "dist/ngx-validate" 24 | ], 25 | "ngx-validate/*": [ 26 | "dist/ngx-validate/*" 27 | ] 28 | } 29 | } 30 | } -------------------------------------------------------------------------------- /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/dist/zone-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: any; 11 | 12 | // First, initialize the Angular testing environment. 13 | getTestBed().initTestEnvironment( 14 | BrowserDynamicTestingModule, 15 | platformBrowserDynamicTesting() 16 | ); 17 | // Then we find all the tests. 18 | const context = require.context('./', true, /\.spec\.ts$/); 19 | // And load the modules. 20 | context.keys().map(context); 21 | -------------------------------------------------------------------------------- /src/environments/environment.ts: -------------------------------------------------------------------------------- 1 | // This file can be replaced during build by using the `fileReplacements` array. 2 | // `ng build --prod` 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/dist/zone-error'; // Included with Angular CLI. 17 | -------------------------------------------------------------------------------- /.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 | 8 | # dependencies 9 | /node_modules 10 | 11 | # profiling files 12 | chrome-profiler-events.json 13 | speed-measure-plugin.json 14 | 15 | # IDEs and editors 16 | /.idea 17 | .project 18 | .classpath 19 | .c9/ 20 | *.launch 21 | .settings/ 22 | *.sublime-workspace 23 | 24 | # IDE - VSCode 25 | .vscode/* 26 | !.vscode/settings.json 27 | !.vscode/tasks.json 28 | !.vscode/launch.json 29 | !.vscode/extensions.json 30 | 31 | # misc 32 | /.sass-cache 33 | /connect.lock 34 | /coverage 35 | /libpeerconnection.log 36 | npm-debug.log 37 | yarn-error.log 38 | testem.log 39 | /typings 40 | 41 | # System Files 42 | .DS_Store 43 | Thumbs.db 44 | -------------------------------------------------------------------------------- /projects/ngx-validate/src/test.ts: -------------------------------------------------------------------------------- 1 | // This file is required by karma.conf.js and loads recursively all the .spec and framework files 2 | 3 | import 'core-js/es7/reflect'; 4 | import 'zone.js/dist/zone'; 5 | import 'zone.js/dist/zone-testing'; 6 | import { getTestBed } from '@angular/core/testing'; 7 | import { 8 | BrowserDynamicTestingModule, 9 | platformBrowserDynamicTesting 10 | } from '@angular/platform-browser-dynamic/testing'; 11 | 12 | declare const require: any; 13 | 14 | // First, initialize the Angular testing environment. 15 | getTestBed().initTestEnvironment( 16 | BrowserDynamicTestingModule, 17 | platformBrowserDynamicTesting() 18 | ); 19 | // Then we find all the tests. 20 | const context = require.context('./lib/', true, /\.spec\.ts$/); 21 | // And load the modules. 22 | context.keys().map(context); 23 | -------------------------------------------------------------------------------- /e2e/protractor.conf.js: -------------------------------------------------------------------------------- 1 | // Protractor configuration file, see link for more information 2 | // https://github.com/angular/protractor/blob/master/lib/config.ts 3 | 4 | const { SpecReporter } = require('jasmine-spec-reporter'); 5 | 6 | exports.config = { 7 | allScriptsTimeout: 11000, 8 | specs: [ 9 | './src/**/*.e2e-spec.ts' 10 | ], 11 | capabilities: { 12 | 'browserName': 'chrome' 13 | }, 14 | directConnect: true, 15 | baseUrl: 'http://localhost:4200/', 16 | framework: 'jasmine', 17 | jasmineNodeOpts: { 18 | showColors: true, 19 | defaultTimeoutInterval: 30000, 20 | print: function() {} 21 | }, 22 | onPrepare() { 23 | require('ts-node').register({ 24 | project: require('path').join(__dirname, './tsconfig.e2e.json') 25 | }); 26 | jasmine.getEnv().addReporter(new SpecReporter({ spec: { displayStacktrace: true } })); 27 | } 28 | }; -------------------------------------------------------------------------------- /projects/ngx-validate/tsconfig.lib.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "../../tsconfig.json", 3 | "compilerOptions": { 4 | "outDir": "../../out-tsc/lib", 5 | "target": "es2015", 6 | "module": "es2015", 7 | "moduleResolution": "node", 8 | "declaration": true, 9 | "sourceMap": true, 10 | "inlineSources": true, 11 | "emitDecoratorMetadata": true, 12 | "experimentalDecorators": true, 13 | "importHelpers": true, 14 | "types": [], 15 | "lib": [ 16 | "dom", 17 | "es2018" 18 | ] 19 | }, 20 | "angularCompilerOptions": { 21 | "annotateForClosureCompiler": true, 22 | "skipTemplateCodegen": true, 23 | "strictMetadataEmit": true, 24 | "fullTemplateTypeCheck": true, 25 | "strictInjectionParameters": true, 26 | "enableResourceInlining": true 27 | }, 28 | "exclude": [ 29 | "src/test.ts", 30 | "**/*.spec.ts" 31 | ] 32 | } 33 | -------------------------------------------------------------------------------- /projects/ngx-validate/src/lib/ngx-validate.service.ts: -------------------------------------------------------------------------------- 1 | import {Injectable} from '@angular/core'; 2 | import {FormArray, FormControl, FormGroup} from '@angular/forms'; 3 | 4 | @Injectable({ 5 | providedIn: 'root' 6 | }) 7 | export class NgxValidateService { 8 | 9 | constructor() { 10 | } 11 | 12 | /** 13 | * This method will mark each formControl in the form as touched. 14 | * */ 15 | validateAllFormFields(formGroup: FormGroup | any) { 16 | Object.keys(formGroup.controls).forEach(field => { 17 | const control = formGroup.get(field); 18 | if (control instanceof FormControl) { 19 | control.markAsTouched({onlySelf: true}); 20 | } else if (control instanceof FormGroup) { 21 | this.validateAllFormFields(control); 22 | } else if (control instanceof FormArray) { 23 | control.controls.map(c => { 24 | this.validateAllFormFields(c); 25 | }); 26 | } 27 | }); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /src/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-istanbul-reporter'), 13 | require('@angular-devkit/build-angular/plugins/karma') 14 | ], 15 | client: { 16 | clearContext: false // leave Jasmine Spec Runner output visible in browser 17 | }, 18 | coverageIstanbulReporter: { 19 | dir: require('path').join(__dirname, '../coverage'), 20 | reports: ['html', 'lcovonly', 'text-summary'], 21 | fixWebpackSourcePaths: true 22 | }, 23 | reporters: ['progress', 'kjhtml'], 24 | port: 9876, 25 | colors: true, 26 | logLevel: config.LOG_INFO, 27 | autoWatch: true, 28 | browsers: ['Chrome'], 29 | singleRun: false 30 | }); 31 | }; -------------------------------------------------------------------------------- /projects/ngx-validate/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-istanbul-reporter'), 13 | require('@angular-devkit/build-angular/plugins/karma') 14 | ], 15 | client: { 16 | clearContext: false // leave Jasmine Spec Runner output visible in browser 17 | }, 18 | coverageIstanbulReporter: { 19 | dir: require('path').join(__dirname, '../../coverage'), 20 | reports: ['html', 'lcovonly'], 21 | fixWebpackSourcePaths: true 22 | }, 23 | reporters: ['progress', 'kjhtml'], 24 | port: 9876, 25 | colors: true, 26 | logLevel: config.LOG_INFO, 27 | autoWatch: true, 28 | browsers: ['Chrome'], 29 | singleRun: false 30 | }); 31 | }; 32 | -------------------------------------------------------------------------------- /projects/ngx-validate/src/lib/utils/util.ts: -------------------------------------------------------------------------------- 1 | export function isPresent(obj: any): boolean { 2 | return obj !== undefined && obj !== null; 3 | } 4 | 5 | export function isDate(obj: any): boolean { 6 | try { 7 | const date = new Date(obj); 8 | return !isNaN(date.getTime()); 9 | } catch (e) { 10 | return false; 11 | } 12 | } 13 | 14 | export function parseDate(obj: any): string { 15 | try { 16 | // Moment.js 17 | if (obj._d instanceof Date) { 18 | const d = obj._d as Date; 19 | const month = +d.getMonth() + 1; 20 | const day = +d.getDate(); 21 | return `${d.getFullYear()}-${formatDayOrMonth(month)}-${formatDayOrMonth(day)}`; 22 | } 23 | 24 | // NgbDateStruct 25 | if (typeof obj === 'object' && obj.year != null && obj.month != null && obj.day != null) { 26 | const month = +obj.month; 27 | const day = +obj.day; 28 | return `${obj.year}-${formatDayOrMonth(month)}-${formatDayOrMonth(day)}`; 29 | } 30 | } catch (e) { } 31 | return obj; 32 | } 33 | 34 | function formatDayOrMonth(month: number): string|number { 35 | return month < 10 ? `0${month}` : month; 36 | } 37 | -------------------------------------------------------------------------------- /src/app/components/dynamic-field/dynamic-field.directive.ts: -------------------------------------------------------------------------------- 1 | import {ComponentFactoryResolver, Directive, Input, OnInit, ViewContainerRef} from '@angular/core'; 2 | import {FormGroup} from '@angular/forms'; 3 | import {InputComponent} from '../input/input.component'; 4 | import {ButtonComponent} from '../button/button.component'; 5 | import {ControlConfig} from '../../interface/control-config.interface'; 6 | import {SelectComponent} from '../select/select.component'; 7 | 8 | const componentMapper = { 9 | input: InputComponent, 10 | button: ButtonComponent, 11 | select: SelectComponent 12 | }; 13 | 14 | @Directive({ 15 | selector: '[dynamicControl]' 16 | }) 17 | export class DynamicFieldDirective implements OnInit { 18 | @Input() field: ControlConfig; 19 | @Input() group: FormGroup; 20 | componentRef: any; 21 | 22 | constructor( 23 | private cfr: ComponentFactoryResolver, 24 | private container: ViewContainerRef 25 | ) { 26 | } 27 | 28 | ngOnInit() { 29 | // dynamically create component with ComponentFactoryResolver according to field name 30 | const factory = this.cfr.resolveComponentFactory( 31 | componentMapper[this.field.type] 32 | ); 33 | this.componentRef = this.container.createComponent(factory); 34 | this.componentRef.instance.field = this.field; 35 | this.componentRef.instance.group = this.group; 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /src/app/app.module.ts: -------------------------------------------------------------------------------- 1 | import {BrowserModule} from '@angular/platform-browser'; 2 | import {NgModule} from '@angular/core'; 3 | 4 | import {AppComponent} from './app.component'; 5 | import {NgxValidateModule} from '../../projects/ngx-validate/src/lib/ngx-validate.module'; 6 | import {FormsModule, ReactiveFormsModule} from '@angular/forms'; 7 | import {HttpClientModule} from '@angular/common/http'; 8 | import {BrowserAnimationsModule} from '@angular/platform-browser/animations'; 9 | import {DynamicFormComponent} from './components/dynamic-form/dynamic-form.component'; 10 | import {InputComponent} from './components/input/input.component'; 11 | import {ButtonComponent} from './components/button/button.component'; 12 | import {DynamicFieldDirective} from './components/dynamic-field/dynamic-field.directive'; 13 | import {SelectComponent} from './components/select/select.component'; 14 | 15 | 16 | @NgModule({ 17 | declarations: [ 18 | AppComponent, 19 | DynamicFormComponent, 20 | InputComponent, 21 | ButtonComponent, 22 | SelectComponent, 23 | DynamicFieldDirective 24 | ], 25 | imports: [ 26 | BrowserModule, 27 | NgxValidateModule, 28 | ReactiveFormsModule, 29 | HttpClientModule, 30 | BrowserAnimationsModule, 31 | FormsModule 32 | ], 33 | entryComponents: [ 34 | InputComponent, 35 | ButtonComponent, 36 | SelectComponent 37 | ], 38 | providers: [], 39 | bootstrap: [AppComponent] 40 | }) 41 | export class AppModule { 42 | } 43 | -------------------------------------------------------------------------------- /projects/ngx-validate/src/lib/validation-error/validation-error.component.html: -------------------------------------------------------------------------------- 1 |
2 |

Field is required

3 |

The email is invalid

4 |

The field is too small

5 |

The field is too large

6 |

The field is too short

7 |

The field is too long

8 |

Only number or '+' or '-' or '.' allowed

9 |

The password is not strong enough

10 |

The password is not match

11 |

The field allows number or letter only

12 |

The field allows space or letter only

13 |

The field should not contain blank

14 |

The field duplicate with server

15 |

The field should be url

16 |
17 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "ngx-validate-lib", 3 | "version": "0.0.0", 4 | "scripts": { 5 | "ng": "ng", 6 | "start": "ng serve", 7 | "build": "ng build", 8 | "test": "ng test", 9 | "lint": "ng lint", 10 | "e2e": "ng e2e" 11 | }, 12 | "private": true, 13 | "dependencies": { 14 | "@angular/animations": "~7.1.0", 15 | "@angular/common": "~7.1.0", 16 | "@angular/compiler": "~7.1.0", 17 | "@angular/core": "~7.1.0", 18 | "@angular/forms": "~7.1.0", 19 | "@angular/platform-browser": "~7.1.0", 20 | "@angular/platform-browser-dynamic": "~7.1.0", 21 | "@angular/router": "~7.1.0", 22 | "core-js": "^2.5.4", 23 | "ngx-validate": "^0.0.15", 24 | "rxjs": "~6.3.3", 25 | "tslib": "^1.9.0", 26 | "zone.js": "~0.8.26" 27 | }, 28 | "devDependencies": { 29 | "@angular-devkit/build-angular": "~0.11.0", 30 | "@angular-devkit/build-ng-packagr": "~0.11.0", 31 | "@angular/cli": "~7.1.2", 32 | "@angular/compiler-cli": "~7.1.0", 33 | "@angular/language-service": "~7.1.0", 34 | "@types/jasmine": "~2.8.8", 35 | "@types/jasminewd2": "~2.0.3", 36 | "@types/node": "~8.9.4", 37 | "codelyzer": "~4.5.0", 38 | "jasmine-core": "~2.99.1", 39 | "jasmine-spec-reporter": "~4.2.1", 40 | "karma": "~3.1.1", 41 | "karma-chrome-launcher": "~2.2.0", 42 | "karma-coverage-istanbul-reporter": "~2.0.1", 43 | "karma-jasmine": "~1.1.2", 44 | "karma-jasmine-html-reporter": "^0.2.2", 45 | "ng-packagr": "^4.2.0", 46 | "protractor": "~5.4.0", 47 | "ts-node": "~7.0.0", 48 | "tsickle": ">=0.29.0", 49 | "tslib": "^1.9.0", 50 | "tslint": "~5.11.0", 51 | "typescript": "~3.1.6" 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /src/app/app.component.ts: -------------------------------------------------------------------------------- 1 | import {Component, ViewChild} from '@angular/core'; 2 | import {FormGroup} from '@angular/forms'; 3 | import {ControlConfig} from './interface/control-config.interface'; 4 | import {DynamicFormComponent} from './components/dynamic-form/dynamic-form.component'; 5 | import {FormConfig} from './data/form-config'; 6 | 7 | @Component({ 8 | selector: 'app-root', 9 | templateUrl: './app.component.html', 10 | styleUrls: ['./app.component.scss'] 11 | }) 12 | export class AppComponent { 13 | @ViewChild(DynamicFormComponent) form: DynamicFormComponent; 14 | formConfig: ControlConfig[] = FormConfig; 15 | 16 | constructor() { 17 | } 18 | 19 | submit(value: any) { 20 | } 21 | 22 | // initFormControl() { 23 | // this.myForm = this.formBuiler.group({ 24 | // name: new FormControl(null, {validators: [Validators.required]} 25 | // ), 26 | // asyncValidate: new FormControl(null, { 27 | // validators: [], 28 | // asyncValidators: [NgxValidators.asyncDuplicate( 29 | // 'http://dummy.restapiexample.com/api/v1/employee/1', this.http, true 30 | // )] 31 | // } 32 | // ), 33 | // requiredWhenNameHasValue: new FormControl(null, { 34 | // validators: [NgxValidators.requiredIfInputHasValue('name')] 35 | // } 36 | // ), 37 | // number: new FormControl('abcd', 38 | // {validators: [Validators.required, NgxValidators.isNumber]} 39 | // ), 40 | // numberLetterOnly: new FormControl(null, 41 | // {validators: [NgxValidators.numberLetterOnly]} 42 | // ), 43 | // password: new FormControl(null, 44 | // { 45 | // validators: [ 46 | // Validators.required, 47 | // NgxValidators.strongPassword 48 | // ] 49 | // }), 50 | // repeatPassword: new FormControl(null, 51 | // {validators: NgxValidators.matchPassword('password')}) 52 | // }); 53 | // } 54 | // 55 | // onSubmit({value, valid}: { value: any, valid: boolean }) { 56 | // if (valid) { 57 | // console.log(value); 58 | // alert(JSON.stringify(value)); 59 | // } else { 60 | // console.log(this.myForm); 61 | // Object.keys(this.myForm.controls).forEach(key => { 62 | // this.ngxValidateService.validateAllFormFields(this.myForm); 63 | // }); 64 | // } 65 | // } 66 | } 67 | -------------------------------------------------------------------------------- /src/app/components/dynamic-form/dynamic-form.component.ts: -------------------------------------------------------------------------------- 1 | import {Component, EventEmitter, Input, OnChanges, OnInit, Output} from '@angular/core'; 2 | import {FormGroup, FormBuilder, Validators, FormControl, FormArray,} from '@angular/forms'; 3 | import {ControlConfig} from '../../interface/control-config.interface'; 4 | 5 | @Component({ 6 | exportAs: 'dynamicForm', 7 | selector: 'dynamic-form', 8 | templateUrl: './dynamic-form.component.html', 9 | styles: [] 10 | }) 11 | export class DynamicFormComponent implements OnInit { 12 | @Input() fields: ControlConfig[] = []; 13 | 14 | @Output() submit: EventEmitter = new EventEmitter(); 15 | 16 | form: FormGroup; 17 | 18 | get value() { 19 | return this.form.value; 20 | } 21 | 22 | constructor(private fb: FormBuilder) { 23 | } 24 | 25 | ngOnInit() { 26 | this.form = this.createControl(); 27 | } 28 | 29 | 30 | // submit form 31 | onSubmit(event: Event) { 32 | console.log('submit'); 33 | event.preventDefault(); 34 | event.stopPropagation(); 35 | if (this.form.valid) { 36 | this.submit.emit(this.form.value); 37 | } else { 38 | this.validateAllFormFields(this.form); 39 | } 40 | } 41 | 42 | createControl() { 43 | const group = this.fb.group({}); 44 | this.fields.forEach(field => { 45 | if (field.type === 'button') { 46 | return; 47 | } 48 | const control = this.fb.control( 49 | field.value, 50 | this.bindValidations(field.validations || []) 51 | ); 52 | group.addControl(field.name, control); 53 | }); 54 | return group; 55 | } 56 | 57 | bindValidations(validations: any) { 58 | if (validations.length > 0) { 59 | const validList = []; 60 | validations.forEach(valid => { 61 | validList.push(valid.validator); 62 | }); 63 | return Validators.compose(validList); 64 | } 65 | return null; 66 | } 67 | 68 | /** 69 | * This method will mark each formControl in the form as touched. 70 | * */ 71 | validateAllFormFields(formGroup: FormGroup | any) { 72 | Object.keys(formGroup.controls).forEach(field => { 73 | const control = formGroup.get(field); 74 | if (control instanceof FormControl) { 75 | control.markAsTouched({onlySelf: true}); 76 | } else if (control instanceof FormGroup) { 77 | this.validateAllFormFields(control); 78 | } else if (control instanceof FormArray) { 79 | control.controls.map(c => { 80 | this.validateAllFormFields(c); 81 | }); 82 | } 83 | }); 84 | } 85 | } 86 | -------------------------------------------------------------------------------- /src/app/data/form-config.ts: -------------------------------------------------------------------------------- 1 | import {ControlConfig} from '../interface/control-config.interface'; 2 | import {Validators} from '@angular/forms'; 3 | import {NgxValidators} from '../../../projects/ngx-validate/src/lib/ngx-validators'; 4 | 5 | export const FormConfig: ControlConfig[] = [ 6 | { 7 | type: 'input', 8 | label: 'Username', 9 | inputType: 'text', 10 | name: 'name', 11 | validations: [ 12 | { 13 | name: 'required', 14 | validator: Validators.required, 15 | message: 'Username Required' 16 | } 17 | ] 18 | }, 19 | { 20 | type: 'input', 21 | label: 'Url', 22 | inputType: 'text', 23 | name: 'url', 24 | validations: [ 25 | { 26 | name: 'isUrlError', 27 | validator: NgxValidators.isUrl, 28 | message: 'Should be a url' 29 | } 30 | ] 31 | }, 32 | { 33 | type: 'select', 34 | label: 'Country', 35 | name: 'country', 36 | value: '', 37 | options: ['', 'India', 'UAE', 'UK', 'US'], 38 | validations: [ 39 | { 40 | name: 'required', 41 | validator: Validators.required, 42 | message: 'Country Required' 43 | } 44 | ] 45 | }, 46 | { 47 | type: 'input', 48 | label: 'Required When Name Has Value', 49 | inputType: 'text', 50 | name: 'requiredIfInputHasValue', 51 | validations: [ 52 | { 53 | name: 'required', 54 | validator: NgxValidators.requiredIfInputHasValue('name'), 55 | message: 'This field is Required' 56 | } 57 | ] 58 | }, 59 | { 60 | type: 'input', 61 | label: 'Number', 62 | inputType: 'text', 63 | name: 'number', 64 | validations: [ 65 | { 66 | name: 'isNumberError', 67 | validator: NgxValidators.isNumber, 68 | message: 'Should be a number here' 69 | } 70 | ] 71 | }, 72 | { 73 | type: 'input', 74 | label: 'Number Letter Only', 75 | inputType: 'text', 76 | name: 'numberLetterOnly', 77 | validations: [ 78 | { 79 | name: 'numberLetterOnlyError', 80 | validator: NgxValidators.numberLetterOnly, 81 | message: 'Should be a number or letter here' 82 | } 83 | ] 84 | }, 85 | { 86 | type: 'input', 87 | label: 'Strong Password', 88 | inputType: 'password', 89 | name: 'password', 90 | validations: [ 91 | { 92 | name: 'strongPasswordError', 93 | validator: NgxValidators.strongPassword, 94 | message: 'Password should contain number and uppercase letter and lower case letter and length should more than 7' 95 | } 96 | ] 97 | }, 98 | { 99 | type: 'input', 100 | label: 'Repeat Password', 101 | inputType: 'password', 102 | name: 'repeatPassword', 103 | validations: [ 104 | { 105 | name: 'matchPasswordError', 106 | validator: NgxValidators.matchPassword('password'), 107 | message: 'The password should match' 108 | } 109 | ] 110 | }, 111 | { 112 | type: 'button', 113 | label: 'Save' 114 | }]; 115 | -------------------------------------------------------------------------------- /tslint.json: -------------------------------------------------------------------------------- 1 | { 2 | "rulesDirectory": [ 3 | "codelyzer" 4 | ], 5 | "rules": { 6 | "arrow-return-shorthand": true, 7 | "callable-types": true, 8 | "class-name": true, 9 | "comment-format": [ 10 | true, 11 | "check-space" 12 | ], 13 | "curly": true, 14 | "deprecation": { 15 | "severity": "warn" 16 | }, 17 | "eofline": true, 18 | "forin": true, 19 | "import-blacklist": [ 20 | true, 21 | "rxjs/Rx" 22 | ], 23 | "import-spacing": true, 24 | "indent": [ 25 | true, 26 | "spaces" 27 | ], 28 | "interface-over-type-literal": true, 29 | "label-position": true, 30 | "max-line-length": [ 31 | true, 32 | 140 33 | ], 34 | "member-access": false, 35 | "member-ordering": [ 36 | true, 37 | { 38 | "order": [ 39 | "static-field", 40 | "instance-field", 41 | "static-method", 42 | "instance-method" 43 | ] 44 | } 45 | ], 46 | "no-arg": true, 47 | "no-bitwise": true, 48 | "no-console": [ 49 | true, 50 | "debug", 51 | "info", 52 | "time", 53 | "timeEnd", 54 | "trace" 55 | ], 56 | "no-construct": true, 57 | "no-debugger": true, 58 | "no-duplicate-super": true, 59 | "no-empty": false, 60 | "no-empty-interface": true, 61 | "no-eval": true, 62 | "no-inferrable-types": [ 63 | true, 64 | "ignore-params" 65 | ], 66 | "no-misused-new": true, 67 | "no-non-null-assertion": true, 68 | "no-redundant-jsdoc": true, 69 | "no-shadowed-variable": true, 70 | "no-string-literal": false, 71 | "no-string-throw": true, 72 | "no-switch-case-fall-through": true, 73 | "no-trailing-whitespace": true, 74 | "no-unnecessary-initializer": true, 75 | "no-unused-expression": true, 76 | "no-use-before-declare": true, 77 | "no-var-keyword": true, 78 | "object-literal-sort-keys": false, 79 | "one-line": [ 80 | true, 81 | "check-open-brace", 82 | "check-catch", 83 | "check-else", 84 | "check-whitespace" 85 | ], 86 | "prefer-const": true, 87 | "quotemark": [ 88 | true, 89 | "single" 90 | ], 91 | "radix": true, 92 | "semicolon": [ 93 | true, 94 | "always" 95 | ], 96 | "triple-equals": [ 97 | true, 98 | "allow-null-check" 99 | ], 100 | "typedef-whitespace": [ 101 | true, 102 | { 103 | "call-signature": "nospace", 104 | "index-signature": "nospace", 105 | "parameter": "nospace", 106 | "property-declaration": "nospace", 107 | "variable-declaration": "nospace" 108 | } 109 | ], 110 | "unified-signatures": true, 111 | "variable-name": false, 112 | "whitespace": [ 113 | true, 114 | "check-branch", 115 | "check-decl", 116 | "check-operator", 117 | "check-separator", 118 | "check-type" 119 | ], 120 | "no-output-on-prefix": true, 121 | "use-input-property-decorator": true, 122 | "use-output-property-decorator": true, 123 | "use-host-property-decorator": true, 124 | "no-input-rename": true, 125 | "no-output-rename": true, 126 | "use-life-cycle-interface": true, 127 | "use-pipe-transform-interface": true, 128 | "component-class-suffix": true, 129 | "directive-class-suffix": true 130 | } 131 | } 132 | -------------------------------------------------------------------------------- /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 Safari >= 10, Chrome >= 55 (including Opera), 12 | * Edge >= 13 on the desktop, and iOS 10 and Chrome on mobile. 13 | * 14 | * Learn more in https://angular.io/guide/browser-support 15 | */ 16 | 17 | /*************************************************************************************************** 18 | * BROWSER POLYFILLS 19 | */ 20 | 21 | /** IE9, IE10 and IE11 requires all of the following polyfills. **/ 22 | // import 'core-js/es6/symbol'; 23 | // import 'core-js/es6/object'; 24 | // import 'core-js/es6/function'; 25 | // import 'core-js/es6/parse-int'; 26 | // import 'core-js/es6/parse-float'; 27 | // import 'core-js/es6/number'; 28 | // import 'core-js/es6/math'; 29 | // import 'core-js/es6/string'; 30 | // import 'core-js/es6/date'; 31 | // import 'core-js/es6/array'; 32 | // import 'core-js/es6/regexp'; 33 | // import 'core-js/es6/map'; 34 | // import 'core-js/es6/weak-map'; 35 | // import 'core-js/es6/set'; 36 | 37 | /** 38 | * If the application will be indexed by Google Search, the following is required. 39 | * Googlebot uses a renderer based on Chrome 41. 40 | * https://developers.google.com/search/docs/guides/rendering 41 | **/ 42 | // import 'core-js/es6/array'; 43 | 44 | /** IE10 and IE11 requires the following for NgClass support on SVG elements */ 45 | // import 'classlist.js'; // Run `npm install --save classlist.js`. 46 | 47 | /** IE10 and IE11 requires the following for the Reflect API. */ 48 | // import 'core-js/es6/reflect'; 49 | 50 | /** 51 | * Web Animations `@angular/platform-browser/animations` 52 | * Only required if AnimationBuilder is used within the application and using IE/Edge or Safari. 53 | * Standard animation support in Angular DOES NOT require any polyfills (as of Angular 6.0). 54 | **/ 55 | // import 'web-animations-js'; // Run `npm install --save web-animations-js`. 56 | 57 | /** 58 | * By default, zone.js will patch all possible macroTask and DomEvents 59 | * user can disable parts of macroTask/DomEvents patch by setting following flags 60 | */ 61 | 62 | // (window as any).__Zone_disable_requestAnimationFrame = true; // disable patch requestAnimationFrame 63 | // (window as any).__Zone_disable_on_property = true; // disable patch onProperty such as onclick 64 | // (window as any).__zone_symbol__BLACK_LISTED_EVENTS = ['scroll', 'mousemove']; // disable patch specified eventNames 65 | 66 | /* 67 | * in IE/Edge developer tools, the addEventListener will also be wrapped by zone.js 68 | * with the following flag, it will bypass `zone.js` patch for IE/Edge 69 | */ 70 | // (window as any).__Zone_enable_cross_context_check = true; 71 | 72 | /*************************************************************************************************** 73 | * Zone JS is required by default for Angular itself. 74 | */ 75 | import 'zone.js/dist/zone'; // Included with Angular CLI. 76 | 77 | 78 | /*************************************************************************************************** 79 | * APPLICATION IMPORTS 80 | */ 81 | -------------------------------------------------------------------------------- /angular.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "./node_modules/@angular/cli/lib/config/schema.json", 3 | "version": 1, 4 | "newProjectRoot": "projects", 5 | "projects": { 6 | "ngx-validate-lib": { 7 | "root": "", 8 | "sourceRoot": "src", 9 | "projectType": "application", 10 | "prefix": "app", 11 | "schematics": { 12 | "@schematics/angular:component": { 13 | "styleext": "scss" 14 | } 15 | }, 16 | "architect": { 17 | "build": { 18 | "builder": "@angular-devkit/build-angular:browser", 19 | "options": { 20 | "outputPath": "dist/ngx-validate-lib", 21 | "index": "src/index.html", 22 | "main": "src/main.ts", 23 | "polyfills": "src/polyfills.ts", 24 | "tsConfig": "src/tsconfig.app.json", 25 | "assets": [ 26 | "src/favicon.ico", 27 | "src/assets" 28 | ], 29 | "styles": [ 30 | "src/styles.scss" 31 | ], 32 | "scripts": [] 33 | }, 34 | "configurations": { 35 | "production": { 36 | "fileReplacements": [ 37 | { 38 | "replace": "src/environments/environment.ts", 39 | "with": "src/environments/environment.prod.ts" 40 | } 41 | ], 42 | "optimization": true, 43 | "outputHashing": "all", 44 | "sourceMap": false, 45 | "extractCss": true, 46 | "namedChunks": false, 47 | "aot": true, 48 | "extractLicenses": true, 49 | "vendorChunk": false, 50 | "buildOptimizer": true, 51 | "budgets": [ 52 | { 53 | "type": "initial", 54 | "maximumWarning": "2mb", 55 | "maximumError": "5mb" 56 | } 57 | ] 58 | } 59 | } 60 | }, 61 | "serve": { 62 | "builder": "@angular-devkit/build-angular:dev-server", 63 | "options": { 64 | "browserTarget": "ngx-validate-lib:build" 65 | }, 66 | "configurations": { 67 | "production": { 68 | "browserTarget": "ngx-validate-lib:build:production" 69 | } 70 | } 71 | }, 72 | "extract-i18n": { 73 | "builder": "@angular-devkit/build-angular:extract-i18n", 74 | "options": { 75 | "browserTarget": "ngx-validate-lib:build" 76 | } 77 | }, 78 | "test": { 79 | "builder": "@angular-devkit/build-angular:karma", 80 | "options": { 81 | "main": "src/test.ts", 82 | "polyfills": "src/polyfills.ts", 83 | "tsConfig": "src/tsconfig.spec.json", 84 | "karmaConfig": "src/karma.conf.js", 85 | "styles": [ 86 | "src/styles.scss" 87 | ], 88 | "scripts": [], 89 | "assets": [ 90 | "src/favicon.ico", 91 | "src/assets" 92 | ] 93 | } 94 | }, 95 | "lint": { 96 | "builder": "@angular-devkit/build-angular:tslint", 97 | "options": { 98 | "tsConfig": [ 99 | "src/tsconfig.app.json", 100 | "src/tsconfig.spec.json" 101 | ], 102 | "exclude": [ 103 | "**/node_modules/**" 104 | ] 105 | } 106 | } 107 | } 108 | }, 109 | "ngx-validate-lib-e2e": { 110 | "root": "e2e/", 111 | "projectType": "application", 112 | "prefix": "", 113 | "architect": { 114 | "e2e": { 115 | "builder": "@angular-devkit/build-angular:protractor", 116 | "options": { 117 | "protractorConfig": "e2e/protractor.conf.js", 118 | "devServerTarget": "ngx-validate-lib:serve" 119 | }, 120 | "configurations": { 121 | "production": { 122 | "devServerTarget": "ngx-validate-lib:serve:production" 123 | } 124 | } 125 | }, 126 | "lint": { 127 | "builder": "@angular-devkit/build-angular:tslint", 128 | "options": { 129 | "tsConfig": "e2e/tsconfig.e2e.json", 130 | "exclude": [ 131 | "**/node_modules/**" 132 | ] 133 | } 134 | } 135 | } 136 | }, 137 | "ngx-validate": { 138 | "root": "projects/ngx-validate", 139 | "sourceRoot": "projects/ngx-validate/src", 140 | "projectType": "library", 141 | "prefix": "lib", 142 | "architect": { 143 | "build": { 144 | "builder": "@angular-devkit/build-ng-packagr:build", 145 | "options": { 146 | "tsConfig": "projects/ngx-validate/tsconfig.lib.json", 147 | "project": "projects/ngx-validate/ng-package.json" 148 | }, 149 | "configurations": { 150 | "production": { 151 | "project": "projects/ngx-validate/ng-package.prod.json" 152 | } 153 | } 154 | }, 155 | "test": { 156 | "builder": "@angular-devkit/build-angular:karma", 157 | "options": { 158 | "main": "projects/ngx-validate/src/test.ts", 159 | "tsConfig": "projects/ngx-validate/tsconfig.spec.json", 160 | "karmaConfig": "projects/ngx-validate/karma.conf.js" 161 | } 162 | }, 163 | "lint": { 164 | "builder": "@angular-devkit/build-angular:tslint", 165 | "options": { 166 | "tsConfig": [ 167 | "projects/ngx-validate/tsconfig.lib.json", 168 | "projects/ngx-validate/tsconfig.spec.json" 169 | ], 170 | "exclude": [ 171 | "**/node_modules/**" 172 | ] 173 | } 174 | } 175 | } 176 | } 177 | }, 178 | "defaultProject": "ngx-validate-lib" 179 | } 180 | -------------------------------------------------------------------------------- /projects/ngx-validate/README.md: -------------------------------------------------------------------------------- 1 | # ngx-validator 2 | 3 | An implementation of various angular validators for Angular 2+. 4 | 5 | Currently support data-driven form only. 6 | 7 | # List of validators 8 | 9 | 1. isNumber(Allow only number or + or - or .) 10 | 1. strongPassword 11 | 1. matchPassword 12 | 1. requiredIfInputHasValue 13 | 1. numberLetterOnly 14 | 1. numberLetterSpaceOnly 15 | 1. noBlank 16 | 1. asyncDuplicate 17 | 18 | # Install 19 | 20 | `npm install ngx-validate` 21 | 22 | 23 | # Example 24 | 25 | [https://angular-ngx-validate-example.stackblitz.io/](https://angular-ngx-validate-example.stackblitz.io/) 26 | 27 | #Code 28 | 29 | Html 30 | 31 | ``` 32 | 33 |
34 |
35 |
36 |
37 |

Angular Reactive Form with NgxValidate

38 |
39 |
40 | 41 | 45 | 46 |
47 | 48 |
49 | 50 | 54 | 55 |
56 | 57 |
58 | 59 | 63 | 64 |
65 | 66 |
67 | 68 | 72 | 73 |
74 | 75 |
76 | 77 | 81 | 82 |
83 | 84 |
85 | 86 |

should contain number and uppercase letter and lower case letter and length should more than 7

87 | 91 | 92 |
93 | 94 | 95 |
96 | 97 | 101 | 102 |
103 | 104 |
105 | 106 |
107 |
108 |
109 |
110 |
111 |
112 | ``` 113 | 114 | Component: 115 | 116 | ``` 117 | class AppComponent { 118 | public myForm: FormGroup; 119 | 120 | constructor(private formBuiler: FormBuilder, 121 | private http: HttpClient, 122 | private ngxValidateService: NgxValidateService) { 123 | this.initFormControl(); 124 | } 125 | 126 | initFormControl() { 127 | this.myForm = this.formBuiler.group({ 128 | name: new FormControl(null, {validators: [Validators.required]} 129 | ), 130 | asyncValidate: new FormControl(null, { 131 | validators: [], 132 | asyncValidators: [NgxValidators.asyncDuplicate( 133 | 'http://dummy.restapiexample.com/api/v1/employee/1', this.http, true 134 | )] 135 | } 136 | ), 137 | requiredWhenNameHasValue: new FormControl(null, { 138 | validators: [NgxValidators.requiredIfInputHasValue('name')] 139 | } 140 | ), 141 | number: new FormControl('abcd', 142 | {validators: [Validators.required, NgxValidators.isNumber]} 143 | ), 144 | numberLetterOnly: new FormControl(null, 145 | {validators: [NgxValidators.numberLetterOnly]} 146 | ), 147 | password: new FormControl(null, 148 | { 149 | validators: [ 150 | Validators.required, 151 | NgxValidators.strongPassword 152 | ] 153 | }), 154 | repeatPassword: new FormControl(null, 155 | {validators: NgxValidators.matchPassword('password')}) 156 | }); 157 | } 158 | 159 | onSubmit({value, valid}: { value: any, valid: boolean }) { 160 | if (valid) { 161 | console.log(value); 162 | alert(JSON.stringify(value)); 163 | } else { 164 | console.log(this.myForm); 165 | Object.keys(this.myForm.controls).forEach(key => { 166 | this.ngxValidateService.validateAllFormFields(this.myForm); 167 | }); 168 | } 169 | } 170 | ``` 171 | 172 | -------------------------------------------------------------------------------- /projects/ngx-validate/src/lib/ngx-validators.ts: -------------------------------------------------------------------------------- 1 | import {AbstractControl, FormControl, ValidationErrors, Validators} from '@angular/forms'; 2 | import {Observable} from 'rxjs'; 3 | import {catchError, map} from 'rxjs/operators'; 4 | import {HttpClient} from '@angular/common/http'; 5 | import {isPresent} from './utils/util'; 6 | 7 | export interface ValidationResult { 8 | [key: string]: boolean; 9 | } 10 | 11 | interface AsyncValidatorFn { 12 | (c: AbstractControl): Promise | Observable; 13 | } 14 | 15 | // https://github.com/ng-packagr/ng-packagr/issues/696 16 | // @dynamic 17 | export class NgxValidators { 18 | /** 19 | * Test if the input is number. 20 | * Allow only number or + or - or . 21 | * If not number, return isNumberError object. 22 | * */ 23 | static isNumber(control: FormControl): ValidationResult { 24 | const customRegexp = /^[\-\+]?[0-9]*(\.[0-9]+)?$/; 25 | if (control.value && !customRegexp.test(control.value)) { 26 | return {isNumberError: true}; 27 | } 28 | } 29 | 30 | /** 31 | * Test if the password strong enough. 32 | * Password should contain number and uppercase letter and lower case letter and length should more than 7 33 | * If not strong enough, return strongPasswordError object. 34 | * */ 35 | public static strongPassword(control: FormControl): ValidationResult { 36 | const hasNumber = /\d/.test(control.value); 37 | const hasUpper = /[A-Z]/.test(control.value); 38 | const hasLower = /[a-z]/.test(control.value); 39 | const valid = hasNumber && hasUpper && hasLower && control.value.length > 7; 40 | if (!valid) { 41 | // return what´s not valid 42 | return {strongPasswordError: true}; 43 | } 44 | return null; 45 | } 46 | 47 | 48 | /** 49 | * Compare two password to validate if they are match 50 | * If not match, return matchPasswordError object. 51 | * */ 52 | static matchPassword(repeatPassword: string) { 53 | 54 | let thisControl: FormControl; 55 | let inputControl: FormControl; 56 | 57 | return function validate(control: FormControl) { 58 | 59 | if (!control.parent) { 60 | return null; 61 | } 62 | 63 | // Initializing the validator. 64 | if (!thisControl) { 65 | thisControl = control; 66 | inputControl = control.parent.get(repeatPassword) as FormControl; 67 | if (!inputControl) { 68 | throw new Error('matchOtherValidator(): other control is not found in parent group'); 69 | } 70 | inputControl.valueChanges.subscribe(() => { 71 | thisControl.updateValueAndValidity(); 72 | }); 73 | } 74 | 75 | if (!inputControl) { 76 | return null; 77 | } 78 | 79 | if (inputControl.value !== thisControl.value) { 80 | return {matchPasswordError: true}; 81 | } 82 | 83 | return null; 84 | }; 85 | } 86 | 87 | /** 88 | * This control is required if the input control has value. 89 | * */ 90 | static requiredIfInputHasValue(inputControlName: string) { 91 | 92 | let thisControl: FormControl; 93 | let inputControl: FormControl; 94 | 95 | return function validate(control: FormControl) { 96 | 97 | if (!control.parent) { 98 | return null; 99 | } 100 | 101 | // Initializing the validator. 102 | if (!thisControl) { 103 | thisControl = control; 104 | inputControl = control.parent.get(inputControlName) as FormControl; 105 | if (!inputControl) { 106 | throw new Error('matchOtherValidator(): other control is not found in parent group'); 107 | } 108 | inputControl.valueChanges.subscribe(() => { 109 | thisControl.updateValueAndValidity(); 110 | }); 111 | } 112 | 113 | if (!inputControl) { 114 | return null; 115 | } 116 | if (inputControl.value && !thisControl.value) { 117 | return { 118 | required: true 119 | }; 120 | } 121 | return null; 122 | }; 123 | } 124 | 125 | 126 | /** 127 | * only allow letters/numbers 128 | * */ 129 | static numberLetterOnly(control: FormControl): ValidationResult { 130 | const regexp = /^[a-zA-Z0-9]*$/; 131 | if (control.value && !regexp.test(control.value)) { 132 | return {numberLetterOnlyError: true}; 133 | } 134 | } 135 | 136 | /** 137 | * only allow letters/numbers/space 138 | * */ 139 | static numberLetterSpaceOnly(control: FormControl): ValidationResult { 140 | const regexp = /^[A-Za-z0-9 _]*$/; 141 | if (control.value && !regexp.test(control.value)) { 142 | return {numberLetterSpace: true}; 143 | } 144 | } 145 | 146 | /** 147 | * should not contain blank 148 | * */ 149 | static noBlank(control: FormControl): { [key: string]: boolean } { 150 | const pattern = '\\s'; 151 | if (new RegExp(pattern).test(control.value)) { 152 | return {'noBlankError': true}; 153 | } 154 | return undefined; 155 | } 156 | 157 | /** 158 | * Validate from backend if this field is duplicate or not. 159 | * Input url string and HttpClient and the validator will get to your url, 160 | * if the response is equal to true -> not duplicate 161 | * if the response is not equal to true -> duplicate 162 | * */ 163 | static asyncDuplicate(url: string, http: HttpClient, expectValue: any): AsyncValidatorFn { 164 | return (control: AbstractControl): Promise | Observable => { 165 | if (control.value) { 166 | return http.get(url, control.value).pipe(map( 167 | res => { 168 | // compare value only here 169 | if (res === expectValue) { 170 | return null; 171 | } else { 172 | return {duplicateError: true}; 173 | } 174 | }, err => { 175 | return {duplicateError: true}; 176 | } 177 | ), catchError((err: any) => { 178 | return null; 179 | })); 180 | } else { 181 | return new Promise((resolve, reject) => { 182 | resolve(null); 183 | } 184 | ); 185 | } 186 | }; 187 | } 188 | 189 | /** 190 | * should not contain blank 191 | * */ 192 | static isUrl(control: FormControl): { [key: string]: boolean } { 193 | if (isPresent(Validators.required(control))) { 194 | return null; 195 | } 196 | 197 | const v: string = control.value; 198 | /* tslint:disable */ 199 | return /^(?:(?:(?:https?|ftp):)?\/\/)(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u00a1-\uffff0-9]-*)*[a-z\u00a1-\uffff0-9]+)(?:\.(?:[a-z\u00a1-\uffff0-9]-*)*[a-z\u00a1-\uffff0-9]+)*(?:\.(?:[a-z\u00a1-\uffff]{2,})).?)(?::\d{2,5})?(?:[/?#]\S*)?$/i.test(v) ? null : {'isUrlError': true}; 200 | /* tslint:enable */ 201 | } 202 | } 203 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # ngx-validator 2 | 3 | An implementation of various angular validators for Angular 2+. 4 | 5 | Currently support data-driven form only. 6 | 7 | # List of validators 8 | 9 | 1. isNumber(Allow only number or + or - or .) 10 | 1. strongPassword 11 | 1. matchPassword 12 | 1. requiredIfInputHasValue 13 | 1. numberLetterOnly 14 | 1. numberLetterSpaceOnly 15 | 1. noBlank 16 | 1. asyncDuplicate 17 | 18 | # Install 19 | 20 | `npm install ngx-validate` 21 | 22 | 23 | # Example 24 | 25 | [https://angular-ngx-validate-example.stackblitz.io/](https://angular-ngx-validate-example.stackblitz.io/) 26 | 27 | #Code 28 | 29 | Html 30 | 31 | ``` 32 |
33 |
34 |
35 |
36 |

Angular Reactive Form with NgxValidate

37 |
38 |
39 | 40 | 44 | 45 |
46 | 47 |
48 | 49 | 59 | 60 |
61 | 62 |
63 | 64 | 68 | 69 |
70 | 71 |
72 | 73 | 77 | 78 |
79 | 80 |
81 | 82 | 86 | 87 |
88 | 89 |
90 | 91 | 95 | 96 |
97 | 98 |
99 | 100 |

should contain number and uppercase letter and lower case letter and length should more than 7

101 | 105 | 106 |
107 | 108 | 109 |
110 | 111 | 115 | 116 |
117 | 118 |
119 | 120 |
121 |
122 |
123 |
124 |
125 |
126 | ``` 127 | 128 | Component: 129 | 130 | ``` 131 | import {Component} from '@angular/core'; 132 | import {FormBuilder, FormControl, FormGroup, Validators} from '@angular/forms'; 133 | import {HttpClient} from '@angular/common/http'; 134 | import {NgxValidateService, NgxValidators} from 'ngx-validate'; 135 | @Component({ 136 | selector: 'my-app', 137 | templateUrl: './app.component.html', 138 | styleUrls: [ './app.component.css' ] 139 | }) 140 | export class AppComponent { 141 | public myForm: FormGroup; 142 | 143 | constructor(private formBuiler: FormBuilder, 144 | private http: HttpClient, 145 | private ngxValidateService: NgxValidateService) { 146 | this.initFormControl(); 147 | } 148 | 149 | initFormControl() { 150 | this.myForm = this.formBuiler.group({ 151 | name: new FormControl(null, {validators: [Validators.required]} 152 | ), 153 | asyncValidate: new FormControl(null, { 154 | validators: [], 155 | asyncValidators: [NgxValidators.asyncDuplicate( 156 | 'http://dummy.restapiexample.com/api/v1/employee/1', this.http, true 157 | )] 158 | } 159 | ), 160 | country: new FormControl(null, {validators: [Validators.required]} 161 | ), 162 | requiredWhenNameHasValue: new FormControl(null, { 163 | validators: [NgxValidators.requiredIfInputHasValue('name')] 164 | } 165 | ), 166 | number: new FormControl('abcd', 167 | {validators: [Validators.required, NgxValidators.isNumber]} 168 | ), 169 | numberLetterOnly: new FormControl(null, 170 | {validators: [NgxValidators.numberLetterOnly]} 171 | ), 172 | password: new FormControl(null, 173 | { 174 | validators: [ 175 | Validators.required, 176 | NgxValidators.strongPassword 177 | ] 178 | }), 179 | repeatPassword: new FormControl(null, 180 | {validators: NgxValidators.matchPassword('password')}) 181 | }); 182 | } 183 | 184 | onSubmit({value, valid}: { value: any, valid: boolean }) { 185 | if (valid) { 186 | console.log(value); 187 | alert(JSON.stringify(value)); 188 | } else { 189 | console.log(this.myForm); 190 | Object.keys(this.myForm.controls).forEach(key => { 191 | this.ngxValidateService.validateAllFormFields(this.myForm); 192 | }); 193 | } 194 | } 195 | } 196 | 197 | ``` 198 | 199 | --------------------------------------------------------------------------------