Angular 6 - Form Validation on blur - angular6

I want to validate input filled in onBlur how can i do this. please help me.
<form class="form-horizontal" role="form" name="form" id="form"
(ngSubmit)="f.form.valid && onSubmit()"
#f="ngForm" novalidate>
<input type="text" class="form-control" placeholder="Social Id"
[ngModel]="generalUserData.socialId" [maxlength]=12 name="socialId" [minlength]=10
(blur)="onBlurMethod($event.target.name, $event.target.value ,generalUserData)"
#socialId="ngModel" [ngClass]="{ 'is-invalid': f.submitted && socialId.invalid }"
pattern="\d{9}(v|V)|\d{12}" required/>
<div *ngIf="f.submitted && socialId.invalid" class="invalid-feedback">
<div *ngIf="socialId?.errors.required">NIC is required</div>
<div *ngIf="socialId?.errors.minlength">NIC must be at least 10 characters long.</div>
<div *ngIf="socialId?.errors.pattern">Not valid NIC</div>
<div *ngIf="socialId?.errors.maxlength">NIC must be less than 12 characters long.</div>
</div>
</form>
I used below sample link and then I want to validate as on blur how can I do this.

The onBlur() method has been changed since Angular 5. With template-driven forms you need to use the following syntax:
<input [(ngModel)]="lastname" [ngModelOptions]="{ updateOn: 'blur' }">
Here is the demo, hope it can help you :
https://codingthesmartway.com/angular5-forms-update/

I update code below like this
<input type="text" class="form-control" placeholder="Social Id"
[ngModel]="generalUserData.socialId" [maxlength]=12 name="socialId" [minlength]=10
(blur)="onBlurMethod($event.target.name, $event.target.value ,generalUserData)"
#socialId="ngModel" [ngClass]="{ 'is-invalid': (f.submitted || socialIdType.touched) && socialId.invalid }"
pattern="\d{9}(v|V)|\d{12}" required/>
<div *ngIf="(f.submitted || socialIdType.touched) && socialId.invalid" class="invalid-feedback">
<div *ngIf="socialId?.errors.required">NIC is required</div>
<div *ngIf="socialId?.errors.minlength">NIC must be at least 10 characters long.</div>
<div *ngIf="socialId?.errors.pattern">Not valid NIC</div>
<div *ngIf="socialId?.errors.maxlength">NIC must be less than 12 characters long.</div>
</div>
now it is working fine.

Related

How can I add eva icon to input ? Angular/Typescript

I am using nebular theme on my project. I am designing login page and I want to add eva user icon to the username input. But I couldn't put the inside of the input.
<form #form='ngForm' class="mb-4" autocomplete="off" (submit)="onSubmit(form)" aria-labelledby="title">
<div class="form-control-group">
<label class="label" for= "input-username">Username :</label>
<input nbInput
fullWidth
type="text"
id="input-username"
placeholder="Username"
fieldSize ="large"
#username="ngModel"
autofocus
name="username"
[(ngModel)]="formModel.username" required
[status]="username.dirty ? (username.invalid ? 'danger' : 'success') : 'basic'">
<ng-container *ngIf="username.invalid && username.touched">
<p class="caption status-danger" *ngIf="username.errors?.required">
Username is required!
</p>
</ng-container>
</div>
Nebular/Input with an icon
Try following codes:
<nb-form-field>
<nb-icon nbPrefix icon="at-outline" pack="eva"></nb-icon>
<input type="text" nbInput>
</nb-form-field>
You can follow their documentation.

Having trouble with validation error messages in Angular

I am having trouble with error messages in my validation. I want to be able to differentiate between the different errors with different messages. How can I fix this. Here is my typescript function:
createFormControl(){
this.updatedArray.forEach((element: any) => {
element.maxlength = +element.maxlength
if(element.required === "true"){
this.xmlForm.addControl(element.name, new FormControl('',[Validators.required, Validators.maxLength(element.maxlength)]));
}else{
this.xmlForm.addControl(element.name, new FormControl(''));
}
});
console.log(this.xmlForm)
}
Here is and example of a part of my HTML:
<div class="row pb-2" [formGroup]="xmlForm">
<div class="col-lg-4" *ngFor="let form of updatedArray">
<div class="form-group" [ngSwitch]="form.type">
<div *ngSwitchCase="'string'">
<label _ngcontent-emf-c46="" for="input1">{{form.name}}</label>
<input _ngcontent-emf-c46="" type="text" [formControlName]="form.name" placeholder="" id="input1" aria-describedby="Text field"
name="name" class="form-control ng-untouched ng-pristine ng-valid" ng-reflect-name="name"
ng-reflect-model="">
<div *ngIf="xmlForm.get(form.name).dirty || xmlForm.get(form.name).touched">
<small class="error" *ngIf="!xmlForm.get(form.name).valid">
{{form.name}} is Required
</small>
</div>
<div *ngIf="xmlForm.get(form.name).dirty">
<small class="error" *ngIf="!xmlForm.get(form.name).valid">
Max Length is {{form.maxlength}}
</small>
</div>
</div>
Both error messages are popping up when one or the other is true. I just want one showing up. How can I fix this?
Instead of *ngIf="!xmlForm.get(form.name).valid" to check for max length compliance, you should try *ngIf="xmlForm.get(form.name).errors?.maxlength". According to the Angular API, the maxlength property becomes available in the errors map if the specified max length is exceeded. You can do a similar check for required using *ngIf="xmlForm.get(form.name).errors?.required"

Input Validation Template Reference ngFor

I am trying to validate an input that is required in a *ngFor loop.
But I cant get a unique template Reference.
On Submit all Input fields are required / or none if at least one is filled out.
I tried to declare Template Reference like #optionContent_{{i}} but i can fill that in [ngClass].
Any help?
<form name="form" (ngSubmit)="f.form.valid && addOption()" #f="ngForm" novalidate>
<div class="row" *ngFor="let size of optionModel.optionContent let i = index">
<div class="col-12">
<label for="optionContent_{{i}}>Name Option</label>
<input id="optionContent_{{i}}"
type="text"
#optionContent="ngModel"
[ngClass]="{ 'is-invalid': f.submitted && optionContent.invalid }"
required
name="optionContent"
[(ngModel)]="size.name" class="form-control">
</div>
</div>
</form>
the problem is in the name attribute they all have the same name, so ngForm gets confused try add dynamic name
<input ... name="optionContent{{i}}" ../>

ERROR TypeError: Cannot read property 'invalid' of undefined angular 5

I am new to Angular 5, I cannot seem to understand why my code is giving the above mentioned error. Please let me know where I am going wrong.
I have initialised all attributes of employee in my .ts file.
<div class="panel-body">
<div class="form-group"
[class.has-error]="name.invalid && name.touched"
[class.has-success]="name.valid">
<label for="name" class="control-label"> Full Name</label>
<input required type="text" id="name" name="name"
[(ngModel)]="employee.name" type="text"
class="form-control" #name="ngModel">
<span class="help-block" *ngIf="name.invalid && name.touched">
Full Name is Required
</span>
</div>
<div>invalid: {{name.invalid}}</div>
Its important to post also your .ts content, but it looks like your are not initializing the name variable when your component loads. you might do this at ngOnInit like this:
ngOnInit(){
this.name = new Foo();
}
Thats why the undefined error
I think your employee object is null .
try :
this.employee = new employee();
this.employee.name = '';
In your .ts file
use safe navigation operator name?.invalid. Here is a working demo : https://stackblitz.com/edit/angular-uv7qbb
<form>
<div class="panel-body">
<div class="form-group"
[class.has-error]="name?.invalid && name?.touched"
[class.has-success]="name?.valid">
<label for="name" class="control-label"> Full Name</label>
<input required type="text" id="name" name="name"
[(ngModel)]="employee.name" type="text"
class="form-control" #name="ngModel">
<span class="help-block" *ngIf="name?.invalid && name?.touched">
Full Name is Required
</span>
</div>
<div>invalid: {{name?.invalid}}</div>
</div>
</form>

input field or help text doesn't turn red when field is invalid

I used to implement an Angular 2/4 application with Bootstrap 3 and used the Reactive Forms approach. I had a field-validation where the border of the input-field turned red and an error message appeared under the field in red font color.
it looks like this:
<div class="form-group row"
[ngClass]="{'has-error': (sourcesForm.get('sourceName').touched ||
sourcesForm.get('sourceName').dirty) &&
!sourcesForm.get('sourceName').valid }">
<label class="col-md-2 col-form-label"
for="sourceNameId">Source Name</label>
<div class="col-md-8">
<input class="form-control"
id="sourceNameId"
type="text"
placeholder="Source Name (required)"
formControlName="sourceName" />
<span class="help-block" *ngIf="(sourcesForm.get('sourceName').touched ||
sourcesForm.get('sourceName').dirty) &&
sourcesForm.get('sourceName').errors">
<span *ngIf="sourcesForm.get('sourceName').errors.required">
Please enter the Source Name.
</span>
<span *ngIf="sourcesForm.get('sourceName').errors.minlength">
The Source Name must be longer than 3 characters.
</span>
<span *ngIf="sourcesForm.get('sourceName').errors.maxlength">
The Source Name is too long.
</span>
</span>
</div>
</div>
Now i have to use Bootstrap 4 and neither the error message or the input-field turns red. How do i realise this? I tried to change the class of the parent span-block to "form-text" but it didn't work.
For beta version of Bootstrap v4, you can check out Form validation docs. There you can read about the new way, supported by all modern browsers for HTML5 way of form-validation with valid/invalid css classes. There Bootstrap uses the .was-validated and .invalid-feedback classes for what you want to achieve (see code snippet).
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css" rel="stylesheet"/>
<form class="container" id="needs-validation" novalidate>
<label for="validationCustom02">Last name</label>
<input type="text" class="form-control" id="validationCustom02" placeholder="Last name" value="Otto" required>
<label for="validationCustom03">City</label>
<input type="text" class="form-control" id="validationCustom03" placeholder="City" required>
<div class="invalid-feedback">
Please provide a valid city.
</div>
<button class="btn btn-primary" type="submit">Submit form</button>
</form>
<script>
// Example starter JavaScript for disabling form submissions if there are invalid fields
(function() {
"use strict";
window.addEventListener("load", function() {
var form = document.getElementById("needs-validation");
form.addEventListener("submit", function(event) {
if (form.checkValidity() == false) {
event.preventDefault();
event.stopPropagation();
}
form.classList.add("was-validated");
}, false);
}, false);
}());
</script>
If you want something more similar to Bootstrap 3, you can use what they call server-side validation, as it is written:
As a fallback, .is-invalid and .is-valid classes may be used instead of the pseudo-classes for server side validation. They do not require a .was-validated parent class.
Previous answer for alpha version of Bootstrap V4 (if you must use this).
On Bootstrap V4 Form Validation Docs there is the following example:
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" rel="stylesheet"/>
<div class="form-group has-danger">
<label class="form-control-label" for="inputDanger1">Input with danger</label>
<input type="text" class="form-control form-control-danger" id="inputDanger1">
<div class="form-control-feedback">Sorry, that username's taken. Try another?</div>
<small class="form-text text-muted">Example help text that remains unchanged.</small>
</div>
So i think you just need to change the has-error class to has-danger
This is the solution:
<div class="form-group row">
<label class="col-md-2 col-form-label"
for="sourceNameId">Source Name</label>
<div class="col-md-8">
<input class="form-control"
[ngClass]="{'is-invalid': (sourcesForm.get('sourceName').touched ||
sourcesForm.get('sourceName').dirty) &&
!sourcesForm.get('sourceName').valid }"
id="sourceNameId"
type="text"
placeholder="Source Name (required)"
formControlName="sourceName" >
<span class="invalid-feedback" *ngIf="(sourcesForm.get('sourceName').touched ||
sourcesForm.get('sourceName').dirty) &&
sourcesForm.get('sourceName').errors">
<span *ngIf="sourcesForm.get('sourceName').errors.required">
Please enter the Source Name.
</span>
<span *ngIf="sourcesForm.get('sourceName').errors.minlength">
The Source Name must be longer than 3 characters.
</span>
<span *ngIf="sourcesForm.get('sourceName').errors.maxlength">
The Source Name is too long.
</span>
</span>
</div>
</div>
i needed to put the [ngClass]into the input-tag. Then i had to define the class as is-invalid and set the parent span-class to invalid-feedback
i know that your question is for long time ago, but it is the best way to validate the form-control input field by reactive form technique and bootstrap 4 to display the validation. first you need to write some code for your form :
in html section:
<form [formGroup]="myForm">
<div class="form-group">
<label for="name">first Name: </label>
<input type="text" class="form-control" formControlName="firstName" id="name">
<div *ngIf="firstName.touched && firstName.invalid" class="alert alert-danger">
<div *ngIf="firstName.errors.required">filling name is required!</div>
</div>
</div>
in ts file, you should implement the logic to conduct the validation.
in ts file:
myForm = new FormGroup({
'firstName':new FormControl('',Validators.required)
})
//getter method
get firstName(){
this.myForm.get('firstName');
}
now you can see that the validation is working. now to give style to input field to show the red border around the invalid input, just go to css file of component and add this class to the css file:
.form-control.ng-touched.ng-invalid{border:2px solid red;}
and simply you can see the result.