nightapes / ngx-validators Goto Github PK
View Code? Open in Web Editor NEWValidator library for Angular 2+
Home Page: https://nightapes.github.io/ngx-validators
License: MIT License
Validator library for Angular 2+
Home Page: https://nightapes.github.io/ngx-validators
License: MIT License
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
Thanks,
Dem
Before:
email: FormControl = new FormControl('', EmailValidators.normal());
After:
email: FormControl = new FormControl('', EmailValidators.normal);
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
@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!
Hi,
How can I combine multiple validators for a single input field?
https://docs.npmjs.com/cli/deprecate
and rename to ngx-validators?
When remove last error, errors = {} and control is invalid.
https://stackblitz.com/edit/angular-reactive-forms-xffegp?file=app/app.component.ts
idea:
static removeError(control: AbstractControl, errorId: string) {
if (control.errors && control.hasError(errorId)) {
if (Object.keys(control.errors).length > 1) {
delete control.errors[errorId];
} else {
control.setErrors(null);
}
}
}
I am using the min , max attribute of the ng2-validators library. The ng-invalid class is not getting removed from the input field even the input is valid.
This makes my whole form invalid. Can you suggest me something if how can i see check the form validity?
Thanks in advance
I am trying to use mismatchedPasswords
for when a user is creating/editing their information, but they are not required to fill out their password again if they have an account and do not wish to change it. Can an option be added that enables a not null check?
Form stays invalid if confirm password is filled up first before the password invalid
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';
~~~~~~~~~~~~~~~~
Hi,
I've got two issues.
The following error is thrown when importing your ValidatorsModule.
ERROR in ValidatorsModule is not an NgModule
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
.
Please add 2-series Master Card validation per this:
https://www.mastercard.us/en-us/issuers/get-support/2-series-bin-expansion.html
New 2-series BIN range will be 222100–272099.
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
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
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.
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.
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.
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.
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
Migrate to Angular 7
Add minDate
and maxDate
directives & validators
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}
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
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
Currently the email check seems to only check for an @
and a .
No TLDs.
Are there still plans on implementing: https://github.com/mailcheck/mailcheck as stated in the readme?
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.