Form validation in angular - html

I am using this html for form validation
I am using Angular 7
-Not working this
What changes need to be done?
<div class="form-group col-sm-6">
<label for="exampleInputPassword1">Email</label>
<input type="text" class="form-control" formControlName="toEmail" >
<div *ngIf="form.controls['toEmail'].errors?.required &&
form.controls['toEmail'].errors?.email">
Enter correct email
</div>
</div>```

try this:
myForm: FormGroup;
constructor(private fb: FormBuilder) {}
ngOnInit() {
this.myForm = this.fb.group({
toEmail: ["", [Validators.required, Validators.email]]
});
}
in your html :
<form #form="ngForm" [formGroup]="myForm" (submit)="onSubmit(form,$event)">
<input formControlName="toEmail" placeholder="Your email">
<p class="text-danger"
[hidden]="myForm.controls['toEmail'].valid || (myForm.controls['toEmail'].pristine && !form.submitted)">
incorrect email address
</p>
<button type="submit">
Send
</button>
</form>
Stackblitz Here

Here is Example
.ts file
myregisterForm: FormGroup;
submitted = false;
constructor(private formBuilder: FormBuilder) { }
ngOnInit() {
this.myregisterForm = this.formBuilder.group({
email: ['', [Validators.required, Validators.email,Validators.pattern('^[a-z0-9._%+-]+#[a-z0-9.-]+\\.[a-z]{2,4}$')]],
password: ['', [Validators.required, Validators.minLength(6)]]
});
}
// convenience getter for easy access to form fields
get f() { return this.myregisterForm.controls; }
onSubmit() {
this.submitted = true;
// stop here if form is invalid
if (this.myregisterForm.invalid) {
return;
}
alert('SUCCESS!! :-)\n\n' + JSON.stringify(this.myregisterForm.value))
}
.html
<form [formGroup]="myregisterForm" (ngSubmit)="onSubmit()">
<div class="form-group">
<label>Email</label>
<input type="text" formControlName="email" class="form-control" [ngClass]="{ 'is-invalid': submitted && f.email.errors }" />
<div *ngIf="submitted && f.email.errors" class="invalid-feedback">
<div *ngIf="f.email.errors.required">Email is required</div>
<div *ngIf="f.email.errors.email">Email must be a valid email address</div>
</div>
</div>
<div class="form-group">
<label>Password</label>
<input type="password" formControlName="password" class="form-control" [ngClass]="{ 'is-invalid': submitted && f.password.errors }" />
<div *ngIf="submitted && f.password.errors" class="invalid-feedback">
<div *ngIf="f.password.errors.required">Password is required</div>
<div *ngIf="f.password.errors.minlength">Password must be at least 6 characters</div>
</div>
</div>
<div class="form-group">
<button class="btn btn-primary">Register</button>
</div>
</form>

Hi try this.
<div class="form-group col-sm-6">
<label for="exampleInputPassword1">Email</label>
<input type="text" class="form-control" formControlName="toEmail" >
<div *ngIf="form.get('toEmail').hasError('required')">
Enter correct email
</div>
</div>

Related

#Input form child component

I am trying to separate the code responsible for the form into another component, and make it reusable.
I guess i should use #Input somehow. Then referr it in html. And pass values from it to post method. But how can i do it?
Backend, form and method worked fine when code were in same .ts. Im using Angular11.2.2
Here is my code:
**camel-form.component.ts **
camelForm = this.formBuilder.group({
id: [],
name: [''],
age: [],
guardian: this.formBuilder.group({
id: [],
name: [''],
lastName: [''],
email: ['']
})
});
**camel-form.component.html **
<form [formGroup]="camelForm">
<!-- part for camel-->
<h2 class="ml-3">Camel form</h2>
<div class="form-row ml-3">
<div class="form-group col-md-2">
<label for="id">id </label>
<input class="form-control" id="id" type="number" formControlName="id">
</div>
<div class="form-group col-md-2">
<label for="name">name </label>
<input class="form-control" id="name" type="text" formControlName="name">
</div>
<div class="form-group col-md-2">
<label for="age">age </label>
<input class="form-control" id="age" type="number" formControlName="age">
</div>
</div>
<!-- part for guardian-->
<h2 class="ml-3">Guardian form</h2>
<div class="form-row ml-3" formGroupName="guardian">
<div class="form-group col-md-2">
<label for="id">id </label>
<input class="form-control" id="id" type="number" formControlName="id">
</div>
<div class="form-group col-md-2">
<label for="name">name </label>
<input class="form-control" id="name" type="text" formControlName="name">
</div>
<div class="form-group col-md-2">
<label for="lastName">lastName</label>
<input class="form-control" id="lastName" type="text" formControlName="lastName">
</div>
<div class="form-group col-md-2">
<label for="email">email</label>
<input class="form-control" id="email" type="email" formControlName="email">
</div>
</div>
</form>
**rest.component.ts **
camel: Camel;
postCamel(): void {
this.camel = this.----------.value;
this.apiService.postCamel(this.camel).subscribe();
}
**rest.component.html **
<app-camel-form></app-camel-form>
<button class="btn-danger ml-3" type="submit" (click)="postCamel()">Submit</button>
First, I would move the submit button into the CamelForm component.
Second, to make the form re-usable for editing you'll need to provide an input for the data so it can be bound to the FormGroup instance. Example, omitting the component definition:
#Input()
camel: ICamel;
form: FormGroup;
initForm(camel?: ICamel): void {
this.form = this.formBuilder.group({
id: [camel ? camel.id : null],
name: [camel ? camel.name : null],
age: [],
guardian: this.formBuilder.group({
id: [camel ? camel.gaurdian.id : null],
name: [camel ? camel.gaurdian.name : null],
lastName: [camel ? camel.gaurdian.lastName : null],
email: [camel ? camel.gaurdian.email : null]
});
}
}
Now you can leverage the form in either case by supplying the input, or not:
<app-camel-form [camel]="camel"></app-camel-instance>
Hope that helps you out.
are you sure you want to make a submit button out of the form? if that is false then you can subscribe to submit event and emit it from your component (submit)="postCamel($event)". Otherwise - you want button out of the form I would propose to do like that
<app-camel-form #camelForm [camel]="camelData"></app-camel-form>
<button (click)="postCamel(camelForm.value)"
and in the form
ngOnChanges(changes) { // this method is needed if you want to pass data to the form
if(changes.camel) {
this.camelForm.patchValue(this.camel)
}
}
get value() {// this will make the form value be accessible from outside of form component
return this.camelForm.value;
}

Add/Remove values from the textboxes in Angular

I would like to add values from the input controls to the applicable divs as displayed in the picture
example.
I followed this Tutorial and I am able to replicate the same controls again and again but not as represented in this picture. This is code, can someone lead me where I went wrong? posted the html and component.ts.
<form [formGroup]="FemaForm" (ngSubmit)="onSubmit()" class="form-horizontal">
<div formArrayName="aliases">
<div *ngFor="let alias of aliases.controls; let i=index">
<label>Cause</label>
<input id="reason" formControlName="cause" type="text" class="form-control"
[formControlName]="i">
<label>Start</label>
<input name="Start" formControlName="Start" type="text"
placeholder="MM/DD/YYYY" [formControlName]="i" />
<label>End</label>
<input name="End" formControlName="End" type="text" placeholder="MM/DD/YYYY" [formControlName]="i" />
<label >FLD</label>
<input id="FLD" formControlName="FLD" type="text" class="form-control"
[formControlName]="i" >
<label>Valid </label>
<input id="Extn" formControlName="Extn" type="text" class="form-control"
[formControlName]="i">
<button (click)="deleteAlias(i)"></button>
</div>
<button (click)="add(i)"> </button>
<button type="submit">Log</button>
</div>
</form>
export class TestComponent {
constructor(private fb: FormBuilder) { }
FemaForm= this.fb.group({
cause: [''],
Start: [''],
End: [''],
FLD: [''],
Extn: [''],
aliases: this.fb.array([
this.fb.control('')
])
});
get aliases() {
return this.FemaForm.get('aliases') as FormArray;
}
add() {
this.aliases.push(this.fb.control(''));
}
deleteAlias(index) {
this.aliases.removeAt(index);
}
}

bind keyup.enter with tab using angular

do someone knows how i can bind the keyup.enter proproty to the tab of the keyboard?
i mean i want that when i enter the value in a first field of my form that i spring in the second field.
Like:
<form>
<label for="xxx">first:
<input type="text" id="first" name="first" (keyup.enter)="enterFirst(firstName)">
</label>
<label for="xxx">second:
<input type="text" id="second" name="second" (keyup.enter)="enterSecond(lastName)">
</label>
.
.
.
<button type="button" class="btn btn-success" (click)="sendNames(xxx)">valid</button>
</form>
So i would to be able to spring on the field second when i give the firstname and click on enter.
Do someone have an idea? thanks in advance
This should work, although it is vanilla JS:
<input type="text" id="first" name="first" onkeyup="if (event.keyCode == '13') {enterFirst(this)}">
(EDITED: Replaced "firstName" with "this")
HTML:
<h1>Here we will try to bind the keyup.enter with Tab</h1>
<div class="container">
<h2>Please enter datas an click on enter</h2>
<form>
<div class="row">
<div class="form-group col">
<label for="fname">Enter your firstname:</label>
<input type="text" class="form-control" placeholder="enter your firstname and click enter"
id="fname" name="fname" onkeyup="if (event.keyCode == '13') {enterFirst(this)}">
</div>
<div class="form-group col">
<label for="lname">Enter your lastname:</label>
<input type="text" class="form-control" placeholder="enter your lastname and click enter"
id="lname" name="lname" onkeyup="if (event.keyCode == '13') {enterLast(this)}">
</div>
</div>
<button type="button" class="btn btn-success" (click)="sendData()">submit</button>
</form>
</div>
Ts:
import { Component, OnInit } from '#angular/core';
#Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent {
title = 'angulartest';
public firstname: string;
constructor(){}
ngOninit(){
}
enterFirst(firstname){
console.log(firstname);
}
sendData(){
}
}
I wrote it just to see if i can spring to the field lastname by clicking on enter after the firstname

Display different error messages if input is empty/incorrect after user touches

I have this same code for two other login/signup components and it works fine, but in this specific component nothing works. No red box pops up under the field saying "email is required" or "password requires" if the user touches the input field and then leaves without typing anything or inputting incorrect information. Is there something wrong here?
Also is my email regex/logic right? My other login page displays "valid email address required" even if the email currently in the input field is something like "test1#gmail.com"
<div class="container">
<div class="form centerForm">
<h1>Child Sign Up</h1>
<form [formGroup]="signUp" (ngSubmit)="onSignUp(signUp)">
<div class="form-group">
<label>Parent ID: </label>
<input placeholder="ID" formControlName="parentID" required />
<div
*ngIf="parentID.invalid && (signUp.submitted || parentID.touched)"
class="alert alert-danger"
>
<div *ngIf="parentID.errors.required">Parent ID is required.</div>
</div>
<br />
</div>
<div class="form-group">
<label>Email: </label>
<input
placeholder="email"
formControlName="email"
required
pattern="/^[^\s#]+#[^\s#]+\.[^\s#]{2,}$/"
/>
<div
*ngIf="email.invalid && (signUp.submitted || email.touched)"
class="alert alert-danger"
>
<div *ngIf="email.errors.required">Email address is required.</div>
<div *ngIf="email.errors.pattern">
Please enter a valid email address.
</div>
</div>
<br />
</div>
<div class="form-group">
<label>Name: </label>
<input
placeholder="first and last name"
formControlName="name"
required
/>
<div
*ngIf="name.invalid && (signUp.submitted || name.touched)"
class="alert alert-danger"
>
<div *ngIf="name.errors.required">Name is required.</div>
</div>
<br />
</div>
<div class="form-group">
<label>Password: </label>
<input
type="password"
formControlName="password"
name="password"
placeholder="Password"
ng-minlength="8"
required
pattern="(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,}"
/>
<div
*ngIf="password.invalid && (signUp.submitted || password.touched)"
class="alert alert-danger"
>
<div *ngIf="password.errors.required">Password is required.</div>
<div *ngIf="password.errors.pattern">
Must contain at least one number and one uppercase and lowercase
letter, and at least 8 or more characters.
</div>
</div>
<br />
</div>
<div class="form-group">
<label>Confirm Password: </label>
<input
type="password"
formControlName="confirmation"
name="confirmPassword"
placeholder="confirm password"
required
pattern="{{ password.value }}"
/>
<div
*ngIf="
confirmation.invalid && (signUp.submitted || confirmation.touched)
"
class="alert alert-danger"
>
<div *ngIf="confirmation.errors.required">
Confirm password is required.
</div>
<div *ngIf="confirmation.errors.pattern">Passwords do not match.</div>
</div>
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
</div>
</div>
In your component initialize your formGroup as follows,
this.signUp = this.formBuilder.group({
email: ['', Validators.required],
name: ['', [Validators.required, Validators.email]],
password : ['', [Validators.required, Validators.minLength(6)]],
confirmation: ['', [Validators.required, Validators.minLength(6)]]
});
In your template use Validation instead of pattern. Also instead of using the formControl signUp.get('email') everytime to get the email, you may use a simple getter,
get email() {
return this.signUp.get('email');
}
Then you can replace signUp.controls['email'] with email everywhere in your template.
<label>Email</label>
<input placeholder="email"
formControlName="email"
required type="text" class="form-control" />
<div *ngIf="(email.dirty || email.touched) && email.invalid && email.errors.required">Email address is required.</div>
<div *ngIf="(email.dirty || email.touched) && email.invalid && email.errors.email">Please enter a valid email address.</div>

How to produce form validations in angularjs2

I am trying to create a from validations in such a way that when form is submitted the invalid fields must be highlighted with red color but i am not sure where i am wrong can someone help me
my template,
<form id="login-form" name="login-form" class="nobottommargin" [formGroup]="form" (ngSubmit)="onSubmit(form.value)">
<p *ngIf="activation" class="activation">We have sent an activation link to your email</p>
<div class="form-group col-sm-offset-2">
<label class="radio-inline">
<input type="radio" [formControl]="form.controls['type']" value = 'personal' name="optradio">Personal
</label>
<label class="radio-inline">
<input type="radio" [formControl]="form.controls['type']" value = 'professional' name="optradio">Professional
</label>
</div>
<div class="form-group">
<input type="text" [formControl]="form.controls['firstname']" id="login-form-firstnamee" name="login-form-firstname" value="" placeholder="First Name" class="sm-form-control not-dark formcontrolheight required">
</div>
<div class="clear"></div>
<div class="col-sm-12 labeltopmargin nopadding">
<button class="col-xs-12 button buttonmeroon button-mini nomargin" id="login-form-submit" name="login-form-submit" value="login">Sign Up</button>
</div>
<div class="clear"></div>
</form>
My ts,
export class SignUp {
http: Http;
emailfailure: any;
activation: any;
profilefailure: any;
form:any;
constructor(fbld: FormBuilder, http: Http, public router: Router) {
this.http = http;
this.form = fbld.group({
firstname: ['', Validators.required],
lastname: ['', Validators.required],
profilename: ['', Validators.required],
email: ['', Validators.required],
password: ['', Validators.required],
repeatpassword: ['', Validators.required],
image: [''],
phone: ['', phoneValidator],
type: ['',],
}
You can use .ng-invalid class which is added to your input, when it does not meet Validator requirements.
You can also display some error messages depending on your form state:
<div class="error message" *ngIf="!form.valid">Your message</div>
This is simple form validation in angular 2
<form #heroForm="ngForm">
<div class="form-group">
<label for="name">Name</label>
<input type="text" class="form-control" id="name"
required
[(ngModel)]="info.name" name="name"
#name="ngModel" >
<span *ngIf="!name.valid && !name.pristine" style="color:red;"> <span>name is Required</span></span>
</div>
<div class="form-group">
<label for="alterEgo">Alter Ego</label>
<input type="text" class="form-control" id="alterEgo"
[(ngModel)]="info.age" name="alterEgo" >
</div>
<button type="button" class="btn btn-default" (click)="enter()">ENTER</button>