Giter Site home page Giter Site logo

nightapes / ngx-validators Goto Github PK

View Code? Open in Web Editor NEW
136.0 136.0 26.0 2.78 MB

Validator library for Angular 2+

Home Page: https://nightapes.github.io/ngx-validators

License: MIT License

JavaScript 1.33% TypeScript 98.67%
angular angular2 angular4 angular7 credit-card ngx-validators phone typescript

ngx-validators's People

Contributors

dependabot[bot] avatar evolkmann avatar fidelisclayton avatar khaledelansari avatar nightapes avatar rafaelss95 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

ngx-validators's Issues

google-libphonenumber dependency adds 366Kb to my vendor file!

Hello,
I was doing some check with source-map-explorer and just saw that ngx-validator contributed for more than 26% of the size of my vendor file (just to compare, the whole material library contributed about 313Kb)...

I think this is not acceptable for a validator library and it's probably better to find an alternative for phone number validations as many ppl will not notice that the size of the vendor file is due to the google-libphonenumber dependency...

At the moment unfortunately the library becomes unusable...

Let me know what you think, I attach a screenshot from source-map-explorer

google_libphonenumber-size

Thanks,
Dem

Errors in library - Not able to run unit test in angular 2 seed project

I'm using ng2-validators for template driven forms validation.
While running unit tests, I am getting below error with ng2-validators :


16 11 2016 17:43:14.668:INFO [Chrome 54.0.2840 (Windows 7 0.0.0)]: Connected on socket NoNtdnDZeME4gr-sAAAA with id 30858027
16 11 2016 17:43:15.493:WARN [web-server]: 404: /node_modules/ng2-validators/package.json
Chrome 54.0.2840 (Windows 7 0.0.0) ERROR: '(SystemJS) XHR error (404 Not Found) loading http://localhost:9876/node_modules/ng2-validators/package.json
        Error: XHR error (404 Not Found) loading http://localhost:9876/node_modules/ng2-validators/package.json
            at XMLHttpRequest.wrapFn [as _onreadystatechange] (http://localhost:9876/base/node_modules/zone.js/dist/zone.js?c35727d0e64913b5669320b167e496fc94fc6928:647:29)
            at ZoneDelegate.invokeTask (http://localhost:9876/base/node_modules/zone.js/dist/zone.js?c35727d0e64913b5669320b167e496fc94fc6928:236:37)
            at Zone.runTask (http://localhost:9876/base/node_modules/zone.js/dist/zone.js?c35727d0e64913b5669320b167e496fc94fc6928:136:47)
            at XMLHttpRequest.ZoneTask.invoke (http://localhost:9876/base/node_modules/zone.js/dist/zone.js?c35727d0e64913b5669320b167e496fc94fc6928:304:33)
        Error loading http://localhost:9876/node_modules/ng2-validators/package.json
        Error loading http://localhost:9876/base/dist/dev/app/user-management/user-management.module.js as "./user-management.module" from http://localhost:9876/base/dist/dev/app/user-management/create-user.component.spec.js'

Finished in 0.001 secs / 0 secs

SUMMARY:
√ 0 tests completed
npm ERR! Test failed. See above for more details.

Please help , this is quite urgent.
Link for angular 2 seed

Project Question

@Nightapes This is an awesome library, however it appears that you have stopped development on it. I was wondering if you would be open to transferring ownership of the repository and the associated npm project, as I would love to take over and work on this project. Please let me know.

Thanks!

Example page

  • add angular cli
  • create github page
  • add example
  • add example code
  • add guide

Mismacth passwords

Form stays invalid if confirm password is filled up first before the password invalid

Build broke after update from 5.0.0 to 5.1.0

Hello all,

our build broke after updating from ngx-validators to 5.1.0. Did something change in the version update?

We are using Angular/core 8.2.2.

import { ValidatorsModule } from 'ngx-validators';
~~~~~~~~~~~~~~~~
app/pages/landing/account/login/login.component.ts:8:33 - error TS2307: Cannot find module 'ngx-validators'.

import { EmailValidators } from 'ngx-validators';
~~~~~~~~~~~~~~~~
app/pages/landing/account/register/register.component.ts:5:36 - error TS2307: Cannot find module 'ngx-validators'.

import { PasswordValidators } from 'ngx-validators';
~~~~~~~~~~~~~~~~

Issues with ValidatorsModule

Hi,

I've got two issues.

  1. The following error is thrown when importing your ValidatorsModule.
    ERROR in ValidatorsModule is not an NgModule

  2. Not sure why, but your email validator does not seem to be recognized in my Model Driven form.

    form: FormGroup;
    
    constructor(protected _fb: FormBuilder) {}
    
    ngOnInit() {
        this.form = this._fb.group({
            'email':   ['', Validators.compose([Validators.required, EmailValidators.normal])],
        });
    }

When I try to display the registered validators {{ form.controls.email.errors | json }} in my template, only the required validator shows up.

I took a quick look at your code, and making the following change caused the form to recognise it.

Before:

export class EmailValidators {
    static simple(): any {
        return function validate(control: AbstractControl): { [key: string]: any } {
            if (Util.isNotPresent(control)) return undefined;
            let pattern = '^.+@.+\\..+$';
            if (new RegExp(pattern).test(control.value)) {
                return undefined;
            }
            return { 'simpleEmailRule': true };
        };
    }

    // https://www.w3.org/TR/html5/forms.html#valid-e-mail-address
    static normal(): any {
        return function validate(control: AbstractControl): { [key: string]: any } {
            if (Util.isNotPresent(control)) return undefined;
            // tslint:disable max-length 
            let pattern = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/
            // tslint:enable
            if (pattern.test(control.value)) {
                return undefined;
            }
            return { 'normalEmailRule': true };
        };
    }
}

After:

export class EmailValidators {
    static simple(control: AbstractControl): any {
        // if (Util.isNotPresent(control)) return undefined;
        let pattern = '^.+@.+\\..+$';
        if (new RegExp(pattern).test(control.value)) {
            return undefined;
        }
    
        return { 'simpleEmailRule': true };
    }
    
    // https://www.w3.org/TR/html5/forms.html#valid-e-mail-address
    static normal(control: AbstractControl): any {
        // if (Util.isNotPresent(control)) return undefined;
        // tslint:disable max-length
        let pattern = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/;
    
        // tslint:enable
        if (pattern.test(control.value)) {
            return undefined;
        }
    
        return { 'normalEmailRule': true };
    }
}

Full discloser, I'm new to angular2, so can you advice as to how to get your library to work please? Using angular 2.4.x.

Angular-seed package

Hi, thanks for your efforts.

I read that validator can be used with angular seed starter, but I don't have such experience (i'm new with angular) and tried 2 methods but all went with errors,
If anyone can help or reproduce for adding ng2-validators and works, can share their setup.

here are my errors:
https://github.com/mgechev/angular-seed my starter setup

editing in /tools/config/project.config.ts

  1. first I tried editing project.config.ts and adding the bundle umd
let additionalPackages: ExtendPackages[] = [
      {
        name: 'ng2-validators',
        path: 'node_modules/ng2-validators/bundles/ng2-validators.umd.js'
      },
    ];
    
    this.addPackagesBundles(additionalPackages);

but when I run npm start it says in console
"(SystemJS) XHR error (404 Not Found) loading http://localhost:5555/node_modules/google-libphonenumber.js
patchProperty/desc.set/wrapFn@http://localhost:5555/node_modules/zone.js/dist/zone.js?1489958749300:1242:26 []
Zone.prototype.runTask@http://localhost:5555/node_modules/zone.js/dist/zone.js?1489958749300:166:28 [ => ]
ZoneTask/this.invoke@http://localhost:5555/node_modules/zone.js/dist/zone.js?1489958749300:420:28 []

Error loading http://localhost:5555/node_modules/google-libphonenumber.js as "google-libphonenumber" from http://localhost:5555/node_modules/ng2-validators/bundles/ng2-validators.umd.js" "Not expecting this error? Report it at https://github.com/mgechev/angular-seed/issues" localhost:5555:67:7

editing in /tools/config/seed.config.ts
2) if I comment (1) in project.config.ts and I add this lines in seed.config.ts

SYSTEM_CONFIG_DEV: any = {
    defaultJSExtensions: true,
    paths: {
      [this.BOOTSTRAP_MODULE]: `${this.APP_BASE}${this.BOOTSTRAP_MODULE}`,
      '@angular/common......
      
      'ng2-validators': 'node_modules/ng2-validators',
      .................
    },
    packages: {
      rxjs: {
        main: "./Rx.js",
        defaultExtension: 'js'
      },
      
      "ng2-validators": {
        main: './index',
        defaultExtension: 'js'
      },
      
    }
  };

it raises i console

"(SystemJS) XHR error (404 Not Found) loading http://localhost:5555/node_modules/traceur.js
patchProperty/desc.set/wrapFn@http://localhost:5555/node_modules/zone.js/dist/zone.js?1489959051078:1242:26 []
Zone.prototype.runTask@http://localhost:5555/node_modules/zone.js/dist/zone.js?1489959051078:166:28 [ => ]
ZoneTask/this.invoke@http://localhost:5555/node_modules/zone.js/dist/zone.js?1489959051078:420:28 []

Error loading http://localhost:5555/node_modules/traceur.js
Unable to load transpiler to transpile http://localhost:5555/node_modules/ng2-validators/index.js
Error loading http://localhost:5555/node_modules/ng2-validators/index.js as "ng2-validators" from http://localhost:5555/app/app.module.js" "Not expecting this error? Report it at https://github.com/mgechev/angular-seed/issues" localhost:5555:67:7

Calling before registerOnValidatorChange is called causes an error

I've been using the isInRange for quite some time already and it's worked great. Though, after moving to Angular 9 (I think) I've started to get an error as follows:

custom-error-handler.ts:11 TypeError: this.onChange is not a function
    at IsInRangeValidatorDirective.ngOnChanges (ngx-validators.js:963)
    at IsInRangeValidatorDirective.wrapOnChangesHook_inPreviousChangesStorage (core.js:27058)
    at callHook (core.js:4712)
    at callHooks (core.js:4672)
    at executeInitAndCheckHooks (core.js:4612)
    at selectIndexInternal (core.js:9661)
    at Module.ɵɵadvance (core.js:9622)
    at GroupSettingsComponent_Template (group-settings.component.html:46)
    at executeTemplate (core.js:12046)
    at refreshView (core.js:11893)

which points to this part of code:

 ngOnChanges(changes: SimpleChanges): void {
    if (changes["minValue"] || changes["maxValue"]) {
      this.validator = UniversalValidators.isInRange(
        changes["minValue"].currentValue,
        changes["maxValue"].currentValue
      );
      this.onChange(); // Line 963
    }
  }

Based on some debugging this is caused by the fact that registerOnValidatorChange is called only after the ngOnChanges is called.

The odd thing about this is that it works in some views and not in other even though I cannot see any obvious difference between the views.

While I don't have a reproduction case available to this, I can grant access to my project for debugging purposes if that helps.

min and max validation are not working when validator @input value change

when I initialize [min] or [max] with some variable, Validation wont work if the variable value change.
For example :

<input name="numberOfDays" [max]="myMax"  #numberOfDays="ngModel" />
<span *ngIf="numberOfDays.hasError('max')">Should be lower or equal to {{ myMax }}</span>

If myMax value change, it wont be considered. The initial value will still be used.

After doing investigations in the source code, I realized the problem is that ngOnInit() is called once when angular instantiate the validator. And this.validator is being initiated in ngOnInit() method with min or max initial value like this.

@Directive({
    ...
})
export class MinValidatorDirective implements Validator, OnInit {
    @Input() min: number;

    private validator: ValidatorFn;
    
    ngOnInit() {
        this.validator = UniversalValidators.min(this.min);
    }
    ...
}

So now, if @Input() min value change, nothing will happen as the ngOnInit() method wont be called again.

A possible solution to this is to reassign this.validator whenever the @Input() min value change.

This a working example:

@Directive({
    ...
})
export class MinValidatorDirective implements Validator, OnInit, OnChanges {
    @Input() min: number;

    private validator: ValidatorFn;
    private onChange: () => void;

    ngOnInit() {
        this.validator = UniversalValidators.min(this.min);
    }

    validate(c: AbstractControl): { [key: string]: any } {
        return this.validator(c);
    }
    
    registerOnValidatorChange(fn: () => void): void {
        this.onChange = fn;
    }
    
    ngOnChanges(changes: SimpleChanges): void {
        if ('min' in changes) {
            this.validator = UniversalValidators.min(this.min);
            if (this.onChange) this.onChange();
        }
    }
}

And I am calling this.onChange() for telling angular to run validation on this formControl since it wont be automatic.

Improve errors by including instantiation parameters

Currently, the errors that are put on the FormControl.errors are just a booleans, however it would be more useful for dynamically displaying error messages to provide an object (whose existence already indicates the error) and has properties containing the parameters used to construct the validator function.

For example, the repeatCharacterRegexRule error should have the number that was passed into it to create the rule.

How to validate on submit?

Let's say I have the following code

<form>
  <input type="text" [(ngModel)]="model.email" name="email" #formControl="ngModel" email />
  <span *ngIf="formControl.hasError('normalEmailRule')">Is not a email</span>
</form>

When I type something it shows the error, but I also want to show the error when the user clicks on submit.

Reactive forms errors code in html

What is the proper way to place the ngx-validators in html when using the Reactive Forms from Angular? I saw a great way to do it in Template-driven forms but unfortunately I am not really interested in them...

I have tried something like this:

<input type="text" class="form-control" formControlName="phone" /> <span *ngIf="phone.hasError('rangeValueToSmall')">Number to small</span> <span *ngIf="phone.hasError('rangeValueToBig')">Number to big</span>

But that does not work at all

Would be extremely thankful if you answer.
Regards,
Mikołaj

Make min and max validators optional to avoid affecting datetime

When using min and max validators althogether with datetime input or ion-datetime this will produce a false error about min or max values not being a number. This happens because min and max values in datetime inputs are not nubmers but datetime strings. For example:

<ion-datetime [min]="2018-02" [max]="2020-04" [(ngModel)]="expDate" #expDate="ngModel"></ion-datetime
<pre>expDate.errors: {{expDate.errors | json}}</pre>

will result in:

{"numberRequired": true}

Add more valid region codes

Hi.

Could you please add 'FR' as a valid region code in ng2-validators/src/phone/phone-validators.ts as it is officially supported by google-libphonenumber ?

Thanks for this wonderful lib. :)

Alan

no whitespace or empty string

Hi, @Nightapes nice work.
I like noWhitespace validator for check if is no whitespace,
but, if in my input I write 'aaa bbb' says that is invalid because have a whitespace.

Hi, is posible to add a validator that can check if a form is empty or a string with only 1 whitespace character?

I think adding this could be good for check if input is not only a whitespace string.
like this, for example, http://stackoverflow.com/questions/39236992/how-to-validate-white-spaces-empty-spaces-angular-2

UniversalValidators.noEmptyString = function (control) {
    if (Util.isNotPresent(control))
        return undefined;
    let isWhitespace = (control.value || '').trim().length === 0;
    let isValid = !isWhitespace;
    return isValid ? undefined : { 'noEmptyString': true }
};

what do you think?
Pere

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.