third774 / ng-bootstrap-form-validation Goto Github PK
View Code? Open in Web Editor NEWAn Angular Module for easy data driven (reactive) form validation
Home Page: https://www.npmjs.com/package/ng-bootstrap-form-validation
License: MIT License
An Angular Module for easy data driven (reactive) form validation
Home Page: https://www.npmjs.com/package/ng-bootstrap-form-validation
License: MIT License
this.formGroup = new FormGroup({
name: new FormControl('', [
Validators.required
]),
phone: new FormControl('', [
Validators.required,
Validators.minLength(8),
Validators.maxLength(10)
]),
email: new FormControl('', [
Validators.required,
Validators.pattern(/^[a-zA-Z0-9.!#$%&’*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/)
]),
password: new FormControl('', [
Validators.required,
Validators.minLength(8),
Validators.maxLength(20)
]),
cpassword: new FormControl('', [
Validators.required,
Validators.minLength(8),
Validators.maxLength(20)
])
});
Please help me. thanks.
So when bfv-messages is injected during an input error it is constantly blinking due to the change detection. The problem is if I am in developer tools it prevents me from copying stuff in the styles tab unless i first remove the error message manually or if I expand the bfv-messages element, just makes it a hassle to work within the developer tools area
Is this something that can be prevented?
Looking over the final style classes for bs4 I believe it would be possible to support both version 3 and 4 simultaneously out-of-the-box. I'd like to discuss if this is something that should be done. While it might not be the cleanest and most general approach, this is a bootstrap themed validation library so I don't think it's completely out of scope.
I have a form when I click the submit button the page gets reloaded. I don't understand why this is happenning.
Hello
I'd like to use this with ngx-translate.
Is this somewhere on your roadmap?
After import NgBootstrapFormValidationModule.forRoot() into app.module
that compile error and show message below
./node_modules/ng-bootstrap-form-validation/node_modules/@angular/core/@angular/core.es5.js
5659:15-36 Critical dependency: the request of a dependency is an expression
@ ./node_modules/ng-bootstrap-form-validation/node_modules/@angular/core/@angular/core.es5.js
@ ./node_modules/ng-bootstrap-form-validation/ng-bootstrap-form-validation/ng-bootstrap-form-validation.es5.js
@ ./src/app/app.module.ts
@ ./src/main.ts
@ multi webpack-dev-server/client?http://0.0.0.0:0 ./src/main.ts
Does anyone have any solution?
Environment
Hi, I have a few doubts:
How to display errors while the user is typing instead of when he clicks away of the input?
How to disable the green styling when a field has no errors?
hello there,
firstly ,A big thank you for your time and effort on this module this is by far the easiest the best validation module aroud !
So i'm pretty much new to Angular.
So how can i style or make this validation text appear as a tool tip ?
It would be really helpful if you can elaborate or share a snippet.
btw i use ngx-bootstrap !!
Hi.
I've a form with an array of forms. For example:
this.formGroup = this.formBuilder.group({
'field1': [null, Validators.required],
'field2': this.formBuilder.array([]),
});
Field2 is a form group with some fields required. The form is not submit because some fields on Field2 are not valid, but no message is shown, nor fields are marked with has-error class.
Getting the error below when either i run ng build or ng serve
ERROR in node_modules/@angular/core/src/render3/ng_dev_mode.d.ts(9,11): error TS2451: Cannot redeclare block-scoped variable 'ngDevMode'.
node_modules/ng-bootstrap-form-validation/node_modules/@angular/core/src/render3/ng_dev_mode.d.ts(9,11): error TS2451: Cannot redeclare block-scoped variable 'ngDevMode'.
Angular 4.4.0-RC.0
When adding NgBootstrapFormValidationModule.forRoot() to my app.moudle.ts it compiles ok but i get the following error in browser:
Unexpected value '[object Object]' imported by the module 'AppModule'. Please add a @NgModule annotation.
The latest version on NPM is currently 1.0.11.
If you're having issues with the package using Angular 5, please manually install version 2.0.1
using
npm install [email protected]
I'll publish a new patch version 2.0.2
tonight with no changes to rectify this.
@third774 Is there any particular reason, that you know of, that we should restrict this selector to form
elements? In checking the FormGroupDirective
, the selector there is simply [formGroup]
.
https://angular.io/api/forms/FormGroupDirective
@Directive({
selector: '[formGroup]',
providers: [formDirectiveProvider],
host: { '(submit)': 'onSubmit($event)', '(reset)': 'onReset()' },
exportAs: 'ngForm'
})
class FormGroupDirective extends ControlContainer implements Form, OnChanges { }
@third774 The validation errors are always shown.
How do I show validation errors (if any), only after submit is first clicked?
ErrorMessage[] => [{
error: "minLength",
format: (label, error) => minLengthFormat(label, error)
}]
export function minLengthFormat(label: string, error: any): string {
return error; //<- HERE
}
Angular 8 is out. Would be great to verify support and update package.json.
This release will upgrade to Angular 6, and will add support for Bootstrap 4 (by default). This version does introduce some breaking changes. You can test it now using
npm i ng-bootstrap-form-validation@next
Supports Bootstrap 4!
NgBootstrapFormValidationModule.forRoot()
now accepts an object with configuration options instead of just an array for custom error messages. Furthermore, it defaults to BootstrapVersion.Four
so if you want to continue using it with Bootstrap 3, you'll need to pass in this additional argument. Alternatively, you may also provide the BootstrapVersion
value using the BOOTSTRAP_VERSION
token.
import {
NgBootstrapFormValidationModule,
BootstrapVersion,
BOOTSTRAP_VERSION
} from 'ng-bootstrap-form-validation';
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
@NgModule({
declarations: [AppComponent],
imports: [
BrowserModule,
FormsModule,
ReactiveFormsModule,
NgBootstrapFormValidationModule.forRoot({
bootstrapVersion: BootstrapVersion.Three, // Defaults to Four
customErrorMessages: []
})
],
providers: [
// Alternatively, you can provide the BootstrapVersion value
// using the BOOTSTRAP_VERSION token
// {
// provide: BOOTSTRAP_VERSION,
// useValue: BootstrapVersion.Three
// }
],
bootstrap: [AppComponent]
})
export class AppModule {}
If we have a form horizontal as Bootstrap 3 says:
<div class="form-group">
<label class="control-label col-md-3">Título</label>
<div class="col-md-9">
<input type="text" formControlName="name" class="form-control">
</div>
</div>
The error is placed outside col-md-9 div. It must be inside to view message correctly.
Angular allows validating multiple fields at once and output a per form validation. Documented here: https://angular.io/guide/form-validation#cross-field-validation
Is there a way to tell ng-bootstrap-form-validation to also listen on such validation results?
The validSubmit
attribute of FormValidationDirective
is emitted based on FormGroup's current status, as shown here -
if (this.formGroup.valid) {
this.validSubmit.emit(this.formGroup.value);
}
So if we're using an async validator, this condition will be false until async validation is resolved.
PR coming up...
I am trying to figure out how to display error messages from the server. For example if I try to save something and I get a response that the name is a duplicate (or any other server side validation failed)
Basically when the submit ajax is fired if I get a 422 i then want to loop through the returned errors and then set the appropriate control to an error and then display the message.
Something along the lines of below. It sets the control red and does all that, but I dont know how to get the message to display under the control (err[field] is the message). I have the errors returning as {field: message}
err => {
for ( const field in err) {
this.form.controls[field].setErrors({"error": err[field]});
}
}
Sometimes it's useful to have the actual error value when defining custom errors.
What we have right now:
format: (label, error)
Would be useful to have:
format: (label, error, errorValue)
WARNING in ./node_modules/ng-bootstrap-form-validation/node_modules/@angular/core/@angular/core.es5.js
5659:15-36 Critical dependency: the request of a dependency is an expression
at ImportLazyContextDependency.getWarnings (/node_modules/webpack/lib/dependencies/ContextDependency.js:39:18)
How to fix this?
Hi.
All worked fine, but I need an async validation on a field. When I put it, I get an error:
ERROR TypeError: Cannot convert undefined or null to object
at Function.keys (<anonymous>)
at ng-bootstrap-form-validation.es5.js:195
at Array.forEach (<anonymous>)
at FormGroupComponent.get [as messages] (ng-bootstrap-form-validation.es5.js:194)
at Object.eval [as updateDirectives] (FormGroupComponent.html:3)
at Object.debugUpdateDirectives [as updateDirectives] (core.es5.js:13067)
at checkAndUpdateView (core.es5.js:12251)
at callViewAction (core.es5.js:12599)
at execComponentViewsAction (core.es5.js:12531)
at checkAndUpdateView (core.es5.js:12257)
The line 195 is inside this method:
Object.defineProperty(FormGroupComponent.prototype, "messages", {
/**
* @return {?}
*/
get: function () {
var _this = this;
var /** @type {?} */ messages = [];
if (!this.isDirtyAndTouched || this.validationDisabled)
return messages;
this.FormControlNames.filter(function (c) { return !c.valid; }).forEach(function (control) {
Object.keys(control.errors).forEach(function (key) { // <---- line 195
var /** @type {?} */ error = _this.errorMessages.find(function (error) { return error.error === key; });
if (!error)
return;
messages.push(error.format(_this.label, control.errors[key]));
});
});
return messages;
},
enumerable: true,
configurable: true
});
I don't know what happens exactly. I think that the event is thrown when sync validations are done, but as field is marked as not valid but there is no errors (the field has erros = null), that line does not check if t's null and breaks.
I'm trying to validate on other ways, but i'm frustrating by the needed logic. Can you help me please? Any working example to manage the async validation on a field with reactive forms?
Thanks in advance.
Sergio
Since v3.0.0
is out, we ought to update the README.md
to use Bootstrap 4 since that's now the default.
Hi, thank you for the module, it's great!.
Currently we are using automatic tests to check our application, and we get the web page elements by ID. We have notice that the html code of the validation messages doesn't contain an ID.
For example:
<bfv-messages _nghost-c4="" ng-reflect-messages="function () { return _this.get">
<span _ngcontent-c4="" class="invalid-feedback" ng-reflect-ng-class="invalid-feedback">This field must be at least 4 characters</span>
</bfv-messages>
Is it any possibility to add an unique ID to "span" element?
Thank you.
Let's say I have two form fields:
one which will contain a phone number,
another one which will contain a first name.
Using this package, how can I set the message "the phone number must be of 10 digits" for the first field, and "the first name can only contain letters" for the second one? As far as I know, I can only set one error message per error kind..
If we receive errors from the server, they need to be inserted into the form, and the validation errors updated.
I've updated the reactive form using
const control = this.myForm.get("controlName");
control.setErrors({ error: "some error from the server" });
control.markAsDirty();
control.markAsTouched();
control.updateValueAndValidity();
I hoped that would be all I need to do, but the validation errors are not updated. So there's obviously more to be done.
Has anyone got an example of how to trigger an update in the template after the form is updated?
There are instances where I do not want show default error messages but a customized one that too based on custom logic. Hence, it would be great if this enhancement is added.
According to bootstrap 4 Replaced the .has-error, .has-warning, and .has-success classes with HTML5 form validation via CSS’s :invalid and :valid pseudo-classes.
hence no styling is showing for errors.
Hi,
I'm using this library and overall it seems to work just fine. However, I have some cases where I have inputs styled as form-control
, without actually using them within a <form>
tag.
When I combine that with these directives, the application breaks with the following error:
ERROR TypeError: Cannot read property 'getControl' of null
at FormControlDirective.get [as control] (ng-bootstrap-form-validation.js:413)
at FormControlDirective.get [as validClass] (ng-bootstrap-form-validation.js:372)
I suspect the culprit is the following line of code:
The assumption made here is that formDirective
must be defined, however when looking at the getter for formDirective
, it says:
get formDirective(): any {
return this.parent ? this.parent.formDirective : null;
}
Which means a null value could be returned, which in turn results in the error I've described above.
Currently, if an input has more than one error, each error message will be rendered.
It would be easy enough to implement a toggle for showing all or one message, but which option should be on by default? Which one provides the best user experience?
Displaying all seems like the best default behavior as it will allow the user to know what criteria must be satisfied all at once.
Does anyone else have opinions regarding this?
Hi there,
First off, I'd like to say; nice module, thanks for sharing it!
I'm actually using this for a Bootstrap 4 based project and for the most part it works great. However in bootstrap 4(alpha,beta) the help block's classes have changed. I was wondering if you had any thoughts on a nice clean way that could be customized. Obviously another parameter to the forRoot
method would work, but that seems a bit excessive.
For now, I'm using Bootstrap 4 alpha, so I've patched the help block class:
.help-block { @extend .form-control-feedback; }
Which works perfectly and is fairly unintrusive.
Anyways, I just figured it might be a topic worth discussing, thanks again.
I have form that when I push in "Save" button the form get validated correctly but I have a toggle control that when I change the state certain controls (validated prevously) get disabled and it is when throws an exception.
I am updating my app for version 6 of RxJs, but in the compilation they indicate errors related to ng-bootstrap-form-validation and RxJs
I am adding server-side validation to FormControls via the setErrors function. The components highlight red however the error messages do not appear.
Is this supported or is there an alternative way to get server-side validation to be displayed?
This was raised in #23 but there was no solution provided from the original user.
ng-packagr is now 2.0.0
, we should consider making this upgrade as part of our 3.0.0
release.
I have added this to my project, that is using bootstrap 4.0 (not beta). It works, expect for the coloring. obviously a css mismatch. a quick look revealed that the validation classes have changed between bs4alpha/beta and the final 4.0 . this project is using classes like 'has-error', while the new classes are 'is-valid', 'is-invalid', etc. as can be seen here:
https://getbootstrap.com/docs/4.0/components/forms/#validation
would be really great if you could update, as this is a true life saver. thanks!
Hi.
Another issue, this is easy to fix.
I have a form without fom controls defined, I submit manually. When I manage changed by click or change events, all works fine. But if I press enter key on an input, it throws an error because there is no controls.
ERROR TypeError: Cannot read property 'controls' of undefined
at FormValidationDirective.webpackJsonp.../../../../ng-bootstrap-form-validation/ng-bootstrap-form-validation/ng-bootstrap-form-validation.es5.js.FormValidationDirective.markAsTouchedAndDirty (ng-bootstrap-form-validation.es5.js:23)
On the code, it assumes that there are controls on the form (2nd line of the function):
/**
* @param {?} formGroup
* @return {?}
*/
FormValidationDirective.prototype.markAsTouchedAndDirty = function (formGroup) {
var _this = this;
Object.keys(formGroup.controls).forEach(function (key) {
if (formGroup.controls[key] instanceof FormGroup) {
_this.markAsTouchedAndDirty(/** @type {?} */ (formGroup.controls[key]));
}
else {
formGroup.controls[key].markAsDirty();
formGroup.controls[key].markAsTouched();
formGroup.controls[key].updateValueAndValidity();
}
});
};
This error can be prevented if input variable is checked of undefined, and in this case, do nothing.
I'll try to fix it and make a pull-request.
Hi Guys,
After installing the 3.0.0 RC today, i keep getting a weird compiler error. (In the browser, not in the console running ng serve).
What makes it weirder for me (as a noob), is when i run it as AOT instead of JIT. It works without any error.
compiler.js:1016 Uncaught Error: Can't resolve all parameters for FormControlDirective: (?, [object Object]).
at syntaxError (compiler.js:1016)
at CompileMetadataResolver.push../node_modules/@angular/compiler/fesm5/compiler.js.CompileMetadataResolver._getDependenciesMetadata (compiler.js:10917)
at CompileMetadataResolver.push../node_modules/@angular/compiler/fesm5/compiler.js.CompileMetadataResolver._getTypeMetadata (compiler.js:10810)
at CompileMetadataResolver.push../node_modules/@angular/compiler/fesm5/compiler.js.CompileMetadataResolver.getNonNormalizedDirectiveMetadata (compiler.js:10429)
at CompileMetadataResolver.push../node_modules/@angular/compiler/fesm5/compiler.js.CompileMetadataResolver.loadDirectiveMetadata (compiler.js:10291)
at compiler.js:23857
at Array.forEach (<anonymous>)
at compiler.js:23856
at Array.forEach (<anonymous>)
at JitCompiler.push../node_modules/@angular/compiler/fesm5/compiler.js.JitCompiler._loadModules (compiler.js:23853)
FYI: I installed it thru Yarn and my ng version is:
Angular CLI: 6.1.5
Node: 9.2.1
OS: darwin x64
Angular: 6.1.6
... animations, common, compiler, compiler-cli, core, forms
... http, language-service, platform-browser
... platform-browser-dynamic, router
Package Version
-----------------------------------------------------------
@angular-devkit/architect 0.7.5
@angular-devkit/build-angular 0.7.5
@angular-devkit/build-optimizer 0.7.5
@angular-devkit/build-webpack 0.7.5
@angular-devkit/core 0.7.5
@angular-devkit/schematics 0.7.5
@angular/cli 6.1.5
@ngtools/webpack 6.1.5
@schematics/angular 0.7.5
@schematics/update 0.7.5
rxjs 6.2.2
typescript 2.7.2
webpack 4.9.2
I'm quite new to Angular, i always try to clean up my sh*t by myself... But today i can't seem to find what i did wrong. All help and comments are appreciated!
Thanks!
Angular 7 is out now! We should upgrade this module and publish a release ASAP so people can use it with the latest and greatest.
Hey i added ng-bootstrap-form-validation to my Angular 8 project and now it validates every form which has [formGroup]. How can i disable it? I already tried Validators.nullValidator and clearValidators().
Error:
Error: Uncaught (in promise): Error: StaticInjectorError[ElementRef]:
StaticInjectorError[ElementRef]:
NullInjectorError: No provider for ElementRef!
Unfortunately, this is affected by ng-packagr/ng-packagr#302, which is a child issue of ng-packagr/ng-packagr#335. For anyone encountering these type errors, you may want to subscribe to the above mentioned issues.
Add support for the new min and max validators added in 4.2.0-beta.0
Any chance to support bootstrap 4.x ?
I know we discussed this in the past, and there was no thrill to do so, but time has passed, and i see more and more systems moving to bootstrap 4, that has different error classes (see below).
I would love to do a pr, but have no clue were to start. give me some clues, and i will jump in.
hopefully it is just changing the class names? thanks.
Here is a sample of how validation should be in bootstrap 4:
<div class="form-group has-danger">
<label class="form-control-label">Username</label>
<input type="text" class="form-control is-invalid">
<div class="invalid-feedback">Sorry, that username's taken. Try another?</div>
</div>
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.