I am new in angular.Email validation is not working in my reactive form validation. I have an error somewhere, but I'm not sure what it is.
Script:
this.loginForm = this.formBulder.group({
fname:['', Validators.required],
lname:['', Validators.required],
email:['', Validators.required],
password:['', Validators.required,Validators.maxLength(5)],
retypepassword:['', Validators.required,Validators.maxLength(5)]
});
https://stackblitz.com/edit/angular-forms-validation-tfzhug?file=app/app.component.html
try to this way
const emailPattern = '[a-zA-Z0-9.-_]{1,}#[a-zA-Z.-]{2,}[.]{1}[a-zA-Z]{2,63}';
mail = new FormControl('',Validators.compose( [Validators.required,Validators.pattern(emailPattern)]));
ts code
import { Component, OnInit } from '#angular/core';
import { FormGroup, FormBuilder, Validators} from '#angular/forms';
import { UserService } from '../../shared/services/user.service';
const EMAIL_REGEX = /^(([^<>()\[\]\\.,;:\s#"]+(\.[^<>()\[\]\\.,;:\s#"]+)*)|(".+"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
#Component({
selector: 'forget-password',
templateUrl: './forget-password.component.html',
styleUrls: ['./forget-password.component.css']
})
export class ForgetPasswordComponent implements OnInit {
form: FormGroup = new FormGroup({});
errors:any;
failed:boolean=false;
success:boolean=false;
constructor(private userService: UserService,private fb: FormBuilder) {
this.form = this.fb.group({
email: ['', [Validators.required, Validators.email, Validators.pattern(EMAIL_REGEX)]]
});
}
ngOnInit() {
}
get f() {
return this.form.controls;
}
isFieldValid(field: string) {
return (
(this.form.get(field).touched ||
this.form.get(field).untouched) && this.form.get(field).valid
);
}
forgetPassword() {
this.failed=false;
this.success=false;
this.userService.forgetPassword(this.form.value).subscribe(result=>{
this.success=true;
this.form.reset();
},errors=>{
this.failed=true;
this.errors=errors;
})
}
}
View
<form [formGroup]="form" (ngSubmit)="forgetPassword()">
<div class="md-form form-sm mb-2">
<i class="fa fa-envelope prefix"></i>
<input type="text" class="form-control" formControlName="email" type="email"
placeholder="Enter Your Email Address">
<div *ngIf="f.email.touched && f.email.invalid" class="text-danger">
<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="text-center mt-2">
<button class="btn btn-primary" type="submit" [disabled]="!form.valid">Send Password Reset Email
<i class="fa fa-sign-in ml-1"></i>
</button>
</div>
<div *ngIf="failed" class="text-danger" role="alert">
<strong>Oops! </strong> <span *ngFor="let error of errors">{{error}}</span>
</div>
<div *ngIf="success" class="alert alert-success" role="alert">
Successfully change your password
</div>
</form>
you can try this :
this.loginForm = this.formBulder.group({
'fname': new FormControl('',Validators.required),
'lname': new FormControl('',Validators.required),
'email': new FormControl('',[Validators.required,Validators.email]),
'password': new FormControl('',[Validators.required,Validators.maxLength(5)]),
'retypepassword': new FormControl('',[Validators.required,Validators.maxLength(5)]),
});
Related
Been trying to access form instance values bt they are all null..It worked fine in tempalate driven forms. I have imported ReactiveFormsModule. I have played around with the attr but I cant find what am missing??
The form is invalid the moment I use Validators.required meaning its empty
.component.html
<form [formGroup] ="tryForm" (ngSubmit)="onSubmit()" >
<div class="form-group">
<label>Name</label><br>
<input type="text" FormControlName ="name">
<span *ngIf="tryForm.invalid">Name required</span>
</div>
<!-- <div *ngIf="name.invalid" class="alert alert-danger"></div> -->
<div class="form-group">
<label>Email</label><br>
<input type="text" FormControlName ="email">
</div>
<div class="form-group">
<label>Message</label><br>
<input type="text" FormControlName ="message">
</div>
<button type = "submit" >Submit</button>
</form>
.component.ts
import { Component, OnInit } from '#angular/core';
import { FormBuilder, FormControl,FormGroup,Validators} from '#angular/forms';
import { Router} from '#angular/router'
#Component({
selector: 'app-log-in',
templateUrl: './log-in.component.html',
styleUrls: ['./log-in.component.css']
})
export class LogInComponent implements OnInit {
tryForm = this.fb.group({
name : [''],
email: [''],
message: [''],
});
constructor(private fb:FormBuilder,
private router: Router) { }
onSubmit(){
if (this.tryForm.status == "VALID"){
alert("Form Submitted Successfully.")
alert(this.tryForm.get("name")?.value);
this.tryForm.reset();
first you need to change the html FormControlName to formControlName. you can read the full explanation here.
HTML
<form [formGroup]="tryForm" (ngSubmit)="onSubmit(tryForm.value)">
<div class="form-group">
<label>Name</label><br />
<input type="text" formControlName="name" />
<span *ngIf="tryForm.invalid">Name required</span>
</div>
<div class="form-group">
<label>Email</label><br />
<input type="text" formControlName="email" />
</div>
<div class="form-group">
<label>Message</label><br />
<input type="text" formControlName="message" />
</div>
<button type="submit">Submit</button>
</form>
after that change your ts like bellow, make sure you initialize the form on ngOnInit.
TS
export class LogInComponent implements OnInit {
tryForm: FormGroup;
constructor(private fb: FormBuilder) {}
ngOnInit() {
this.createForm();
}
createForm() {
this.tryForm = this.fb.group({
name : [''],
email : [''],
message: [''],
});
}
onSubmit(data) {
console.log(data);
}
}
I replicate your code here
change this <input type="text" FormControlName ="email"> to this;
<input type="text" formControlName="email">
and build your form on ngOnInit,
ngOnInit(){
this.tryForm = this.fb.group({
name : [''],
email: [''],
message: [''],
});
}
I am following the tutorial:
https://jasonwatmore.com/post/2018/10/29/angular-7-user-registration-and-login-example-tutorial
and write a login form according to this by using ReactiveFormsModule in Angular 7
However, after I click on submit with wrong information I just see alert at top for a second and page refreshes itself. I searched a lot about this topic and changing button type does not help.
Here is my HTML code:
<div>
<h2 align="center">Login</h2>
<form [formGroup]="loginForm">
<div class="form-group">
<label for="email">E-mail</label>
<input type="text" formControlName="email" class="form-control" placeholder="your_email#example.com" [ngClass]="{ 'is-invalid': submitted && f.email.errors }" />
<div *ngIf="submitted && f.email.errors" class="invalid-feedback">
<div *ngIf="f.email.errors">Invalid e-mail</div>
</div>
</div>
<div class="form-group">
<label for="password">Password</label>
<input type="password" formControlName="password" placeholder="******" class="form-control" [ngClass]="{ 'is-invalid': submitted && f.password.errors }" />
<div *ngIf="submitted && f.password.errors" class="invalid-feedback">
<div *ngIf="f.password.errors" >Invalid password</div>
</div>
</div>
<div class="form-group">
<button (click)="onSubmit()" [disabled]="loading || !loginForm.controls.email.value || !loginForm.controls.password.value" class="btn btn-primary">Login</button>
<img *ngIf="loading" class="pl-2" src="data:image/gif;base64,R0lGODlhEAAQAPIAAP///wAAAMLCwkJCQgAAAGJiYoKCgpKSkiH/C05FVFNDQVBFMi4wAwEAAAAh/hpDcmVhdGVkIHdpdGggYWpheGxvYWQuaW5mbwAh+QQJCgAAACwAAAAAEAAQAAADMwi63P4wyklrE2MIOggZnAdOmGYJRbExwroUmcG2LmDEwnHQLVsYOd2mBzkYDAdKa+dIAAAh+QQJCgAAACwAAAAAEAAQAAADNAi63P5OjCEgG4QMu7DmikRxQlFUYDEZIGBMRVsaqHwctXXf7WEYB4Ag1xjihkMZsiUkKhIAIfkECQoAAAAsAAAAABAAEAAAAzYIujIjK8pByJDMlFYvBoVjHA70GU7xSUJhmKtwHPAKzLO9HMaoKwJZ7Rf8AYPDDzKpZBqfvwQAIfkECQoAAAAsAAAAABAAEAAAAzMIumIlK8oyhpHsnFZfhYumCYUhDAQxRIdhHBGqRoKw0R8DYlJd8z0fMDgsGo/IpHI5TAAAIfkECQoAAAAsAAAAABAAEAAAAzIIunInK0rnZBTwGPNMgQwmdsNgXGJUlIWEuR5oWUIpz8pAEAMe6TwfwyYsGo/IpFKSAAAh+QQJCgAAACwAAAAAEAAQAAADMwi6IMKQORfjdOe82p4wGccc4CEuQradylesojEMBgsUc2G7sDX3lQGBMLAJibufbSlKAAAh+QQJCgAAACwAAAAAEAAQAAADMgi63P7wCRHZnFVdmgHu2nFwlWCI3WGc3TSWhUFGxTAUkGCbtgENBMJAEJsxgMLWzpEAACH5BAkKAAAALAAAAAAQABAAAAMyCLrc/jDKSatlQtScKdceCAjDII7HcQ4EMTCpyrCuUBjCYRgHVtqlAiB1YhiCnlsRkAAAOwAAAAAAAAAAAA==" />
</div>
<a routerLink="/register" class="go-register">Do you need an account?</a>
</form>
</div>
and TypeScript file:
import { Component, OnInit , OnDestroy} from '#angular/core';
import { Router, ActivatedRoute } from '#angular/router';
import { FormBuilder, FormGroup, Validators} from '#angular/forms';
import { first } from 'rxjs/operators';
import { AuthenticationService } from '../services/auth.service';
import { AlertService } from '../services/alert.service';
#Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {
loginForm: FormGroup;
loading = false;
submitted = false;
returnUrl: string;
error = '';
constructor(
private formBuilder: FormBuilder,
private route: ActivatedRoute,
private router: Router,
private authenticationService: AuthenticationService,
private alertService: AlertService
) { }
ngOnInit() {
this.loginForm = this.formBuilder.group({
email: ['', [Validators.email, Validators.required]],
password: ['', [Validators.pattern('^(?=[^A-Z]*[A-Z])(?=[^a-z]*[a-z])(?=[^0-9]*[0-9]).{6,}$'),
Validators.minLength(6),
Validators.required]]
});
// reset login status
this.authenticationService.logout();
// get return url from route parameters or default to '/'
this.returnUrl = this.route.snapshot.queryParams.returnUrl || '/';
}
// convenience getter for easy access to form fields
get f() { return this.loginForm.controls; }
onSubmit() {
this.submitted = true;
// stop here if form is invalid
if (this.loginForm.invalid) {
return;
}
this.loading = true;
this.authenticationService.login(this.f.email.value, this.f.password.value)
.subscribe(
data => {
this.router.navigate([this.returnUrl]);
},
error => {
this.error = error;
// alert(error);
this.alertService.error(error);
this.loading = false;
});
}
}
I debug my code and I guess problem is about HTML but I cannot resolve.
Also, I tried add event.preventDefault() and (ngSubmit), none of them helped me.
I am open for any ideas...
https://angular.io/guide/reactive-forms#saving-form-data
You have to use ngSubmit...
<form [formGroup]="profileForm" (ngSubmit)="onSubmit()">
Then the default behaviour is disabled and angular handles it.
I'm trying to finalise a register form. I've to do it without using the form tag.
I've this registerform:
<div class="row">
<div class="center col-xs-8 col-xs-offset-2">
<p class="h5 text-center mb-4">{{ 'Signup' | translate }}</p>
<div class="form-group">
<label for="email">{{ 'SignupEmail' | translate }}</label>
<input type="text" [(ngModel)]="user.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 for="username">{{ 'SignupUsername' | translate }}</label>
<input type="text" [(ngModel)]="user.name" class="form-control" [ngClass]="{ 'is-invalid': submitted && f.email.errors }" />
</div>
<div class="form-group">
<label for="password">{{ 'SignupPassword' | translate }}</label>
<input type="password" [(ngModel)]="user.password" class="form-control" [ngClass]="{ 'is-invalid': submitted && f.email.errors }" />
</div>
<div class="form-group">
<label for="birth">{{ 'SignupBirth' | translate }}</label>
<input type="date" [(ngModel)]="user.dateNaissance" class="form-control" [ngClass]="{ 'is-invalid': submitted && f.email.errors }" />
</div>
<div class="form-group">
<button [disabled]="loading" class="btn btn-info" (click)="onSubmit()" >{{ 'SignupSubmit' | translate }}</button>
<img *ngIf="loading" src="data:image/gif;base64,R0lGODlhEAAQAPIAAP///wAAAMLCwkJCQgAAAGJiYoKCgpKSkiH/C05FVFNDQVBFMi4wAwEAAAAh/hpDcmVhdGVkIHdpdGggYWpheGxvYWQuaW5mbwAh+QQJCgAAACwAAAAAEAAQAAADMwi63P4wyklrE2MIOggZnAdOmGYJRbExwroUmcG2LmDEwnHQLVsYOd2mBzkYDAdKa+dIAAAh+QQJCgAAACwAAAAAEAAQAAADNAi63P5OjCEgG4QMu7DmikRxQlFUYDEZIGBMRVsaqHwctXXf7WEYB4Ag1xjihkMZsiUkKhIAIfkECQoAAAAsAAAAABAAEAAAAzYIujIjK8pByJDMlFYvBoVjHA70GU7xSUJhmKtwHPAKzLO9HMaoKwJZ7Rf8AYPDDzKpZBqfvwQAIfkECQoAAAAsAAAAABAAEAAAAzMIumIlK8oyhpHsnFZfhYumCYUhDAQxRIdhHBGqRoKw0R8DYlJd8z0fMDgsGo/IpHI5TAAAIfkECQoAAAAsAAAAABAAEAAAAzIIunInK0rnZBTwGPNMgQwmdsNgXGJUlIWEuR5oWUIpz8pAEAMe6TwfwyYsGo/IpFKSAAAh+QQJCgAAACwAAAAAEAAQAAADMwi6IMKQORfjdOe82p4wGccc4CEuQradylesojEMBgsUc2G7sDX3lQGBMLAJibufbSlKAAAh+QQJCgAAACwAAAAAEAAQAAADMgi63P7wCRHZnFVdmgHu2nFwlWCI3WGc3TSWhUFGxTAUkGCbtgENBMJAEJsxgMLWzpEAACH5BAkKAAAALAAAAAAQABAAAAMyCLrc/jDKSatlQtScKdceCAjDII7HcQ4EMTCpyrCuUBjCYRgHVtqlAiB1YhiCnlsRkAAAOwAAAAAAAAAAAA==" />
<div class="text-center">
{{ 'SignupAccount1' | translate }} <a routerLink="/login">{{ 'SignupAccount2' | translate }}</a>
</div>
</div>
</div>
</div>
The problem, is that the mail and the other input are always required even if i put a correct address mail in the input. And i don't get why...
Here is the register.component.ts
import {Component, OnInit} from '#angular/core';
import {FormGroup, FormBuilder, Validators} from '#angular/forms';
import {first} from 'rxjs/operators';
import {Router} from '#angular/router';
import {AlertService} from '../services/alert.service';
import {UserService} from '../services/user.service';
#Component({
selector: 'app-register',
templateUrl: './register.component.html',
styleUrls: ['./register.component.sass']
})
export class RegisterComponent implements OnInit {
registerForm: FormGroup;
loading = false;
submitted = false;
user: any;
constructor(private fb: FormBuilder, private router: Router, private userService: UserService, private alertService: AlertService) {
}
ngOnInit() {
this.registerForm = this.fb.group({
username: ['', Validators.required],
//gender: ['', Validators.required],
birth: ['', Validators.required],
email: ['', [Validators.required, Validators.email]],
password: ['', [Validators.required, Validators.minLength(8)]]
});
this.user = new Object();
}
click(ev) {
console.log(ev.target.defaultValue);
}
// convenience getter for easy access to form fields
get f() {return this.registerForm.controls;}
onSubmit() {
this.submitted = true;
// stop here if form is invalid
if (this.registerForm.invalid) {
window.alert("Informations invalides");
return;
}
this.loading = true;
this.userService.register(this.registerForm.value)
.pipe(first())
.subscribe(
data => {
this.alertService.success('Registration successful', true);
this.router.navigate(['/login']);
},
error => {
this.alertService.error(error);
this.loading = false;
});
}
}
Can you help me validate this form (but without adding the form tag)...
Thank you !
You had used reactive form, So use [formGroup] in div and inside that div use formControlName to achieve validation.
Here i have created one reactive form demo with validation and without form tag.
Stackblitz Demo without Form Tag
i'm working on angular 4 form and set some validations on the input field but the validation is show when the page load's but i want the validation when the form is submitted or the email pattern is not valid.
<form [formGroup]="myForm" (ngSubmit)="onSubmit(myForm.value)"
[class.error]="!myForm.valid && myForm.touched">
<div class="field" [class.error]="!email.valid && email.touched">
<label for="email">Email</label>
<input type="email" id="email" name="email" [formControl]="email">
<div *ngIf="!email.valid"
class="ui error message">Email is invalid</div>
<div *ngIf="email.hasError('required')"
class="ui error message">Email is required</div>
</div>
<div *ngIf="!myForm.valid"
class="ui error message">Form is invalid</div>
<button type="submit">login</button>
</form>
Typescript code:
function EmailValidator(control: FormControl): { [s: string]: boolean } {
if (!control.value.match('^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$'))
{
return {invalidEmail: true};
}
}
#Component({
selector: 'app-login-form',
templateUrl: './login-form.component.html',
styleUrls: ['./login-form.component.css']
})
export class LoginFormComponent implements OnInit {
myForm: FormGroup;
email: AbstractControl;
constructor(fb:FormBuilder) {
this.myForm = fb.group({
'Email': ['', Validators.compose([
Validators.required, EmailValidator])
]
});
this.email = this.myForm.controls['Email'];
}
onSubmit(form: string): void {
console.log('you submitted value:', form);
}
}
you can use
<div
*ngIf="myForm.get('email').hasErrors('required') &&
myForm.get('email').touched">
Email is required
</div>
And adapt hasError to your validation
I am trying to upload image but i am getting the error
Here is my template
<h3 class = "head">{{title}}</h3>
<form [ngFormModel]="form" (ngSubmit)="onSubmit(form.value)">
<div class="row">
<div class="form-group">
<label class="formHeading">firstname</label>
<input type="text" id="facebook" class="form-control" ngControl="firstname" #firstname="ngForm" >
</div>
<div *ngIf ="firstname.touched">
<div *ngIf ="!firstname.valid" class = "alert alert-danger">
<strong>First name is required</strong>
</div>
</div>
<div class="form-group">
<label class="formHeading">lastname</label>
<input type="text" id="facebook" class="form-control col-xs-3" ngControl="lastname" #lastname="ngForm" >
</div>
<div *ngIf ="lastname.touched" >
<div *ngIf = "!lastname.valid" class = "alert alert-danger">
<strong>Google name is required</strong>
</div>
</div>
<div class="form-group">
<label class="formHeading">image</label>
<input type="file" id="facebook" class="form-control col-xs-3" ngControl="image" #image="ngForm" >
</div>
<div class="form-row btn">
<button type="submit" class="btn btn-primary pull-right butspace " [disabled]="!form.valid">Save</button>
</div>
</div>
my Component
import {Component} from '#angular/core';
import {Http, Response, Headers} from '#angular/http';
import {Observable} from 'rxjs/Observable';
import {Subject } from 'rxjs/Subject';
import {FORM_DIRECTIVES} from '#angular/common';
import {Control,FormBuilder,ControlGroup,Validators} from '#angular/common';
#Component({
templateUrl: './components/profile/profile.html',
directives: [FORM_DIRECTIVES],})
export class Profile {
http: Http;
form: ControlGroup;
postResponse = new Person();
constructor(fbld: FormBuilder,http: Http) {
this.http = http;
this.form = fbld .group({
firstname: ['', Validators.required],
lastname: ['', Validators.required]
});
}
onSubmit(form){
//this.form = form;
console.log(form);
var headers = new Headers();
// headers.append('Content-Type', 'application/json');
headers.append('Content-Type','application/x-www-form-urlencoded') this.http.post('http://localhost/angular/index.php/profile/addprofile', JSON.stringify(form),{headers:headers})
.map((res: Response) => res.json())
.subscribe((res:Person) => this.postResponse = res);
}
}
class Person{
firstName:string;
lastName:string;
}
It shows the error "Cannot find control 'image' in html file" and i am not able to find the exact issue can someone suggest the error in my code.
I believe the issue is that you have ngControl="image" on one of your inputs, but you never officially made image part of the form in FormBuilder. ngControl is looking for image on the form (to initialize the value), but it can't find it.
Try adding image to this:
this.form = fbld .group({
firstname: ['', Validators.required],
lastname: ['', Validators.required],
image: ['', Validators.required]
});
And maybe here too:
class Person{
firstName:string;
lastName:string;
image: any;
}
Not sure what the data type is for your image, but this is a start.