How can I validate an angular form - javascript

I have this inscription form. I tried to validate it but in vain. inputs are saved in my database despite they are empty I want to have these validations:
All inputs are required
email address should be valid
name should be composer by only letters
Password should have minimum 8 characters, at least 1 uppercase
letter, 1 lowercase letter and 1 number
I want to have a message under evey invalid input.(in <div id="na"></div> for example).How can I do this please?
HTML file
<h2 class="text-center">Inscription</h2>
<div class="row">
<div class="col-md-3">
</div>
<div class="col-md-6 col-md-offset-3">
<div class="jumbotron">
<form [formGroup]="angForm" (ngSubmit)="postdata(angForm)" autocomplete="off">
<div class="form-group mb-3">
<label for="name">Nom</label>
<input type="text" name="name" formControlName="name" autocomplete="off" id="name"
class="form-control input-sm" placeholder="Nom">
</div>
<div id="na"></div>
<div class="form-group mb-3">
<label for="email">Email</label>
<input type="email" name="email" formControlName="email" autocomplete="off" id="email"
class="form-control input-sm" placeholder="Email">
</div>
<div id="mail"></div>
<div class="form-group mb-3">
<label for="Password">Mot de passe</label>
<input type="password" name="Password" formControlName="password" autocomplete="off"
id="password" class="form-control input-sm" placeholder="Mot de passe">
</div>
<div id="pwd"></div>
<button type="sumit" class="btn btn-success">Enregistrer</button>
</form>
</div>
</div>
<div class="col-md-3">
</div>
</div>
Type script file
import { Component, OnInit } from '#angular/core';
import { FormGroup, FormControl, FormBuilder, Validators, NgForm } from '#angular/forms';
import { first } from 'rxjs/operators';
import { Router } from '#angular/router';
import { ApiService } from '../api.service';
#Component({
selector: 'app-inscription',
templateUrl: './inscription.component.html',
styleUrls: ['./inscription.component.css']
})
export class InscriptionComponent implements OnInit {
angForm: FormGroup;
constructor(private fb: FormBuilder,private dataService: ApiService,private router:Router) {
this.angForm = this.fb.group({
email: [],
password: [],
name: [],
mobile: []
});
}
ngOnInit() {
}
postdata(angForm1:any){this.dataService.userregistration(angForm1.value.name,angForm1.value.email,angForm1.value.password)
.pipe(first())
.subscribe(
data => {
this.router.navigate(['login']);
},
error => {
});
}
get email() { return this.angForm.get('email'); }
get password() { return this.angForm.get('password'); }
get name() { return this.angForm.get('name'); }
}
thanks in advance

this.angForm = this.fb.group({
email: ['', Validators.required, Validators.email],
password: ['', Validators.required, Validators.minLength(8), Validators.pattern("(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,}")],
name: ['', Validators.required, Validators.pattern('^[a-zA-Z ]*$')],
mobile: [null, Validators.required, Validators.minLength(10), Validators.maxLength(10)]
});
This is the syntax for Validations.
In HTML, before closing of form-group div write
<span class="text-danger"
*ngIf="(angForm.name.touched || submitted) &&
angForm.name.errors?.required">
Name is required
</span>
<span class="text-danger"
*ngIf="((angForm.password.touched || submitted) &&
angForm.password.errors?.required )|| (angForm.invalid && submitted)">
Must contain at least one number and one uppercase and lowercase letter, and at least 8 or more characters </span>
same applies for email, mobile error msg in HTML.
Please refer for reactive form validation.
https://www.freecodecamp.org/news/how-to-validate-angular-reactive-forms/

response to Rothitha
If you don't want to use the "auxiliar variable" submitted you can use in submit.
submit(form:FormGroup)
{
if (form.invalid)
form.markallAsTouched()
else
{
..doSomething..
}
}
If we can better mannagement about errors (remove this ugly *ngIf="angForm.get('password').touched && angForm.get('password').touched" we can use a tecnica similar bootstrap mannage the error
We use a .css like
.invalid-feedback
{
display:none
}
.ng-invalid.ng-touched ~ .invalid-feedback
{
display: block;
}
And an html like
<!--enclosed all under a div-->
<div>
<!--a label-->
<label for="email">Email</label>
<!--a input-->
<input id="email" formControlName="email">
<!--a div class="invalid-feedback-->
<div class="invalid-feedback">
<!--if there're several validators use *ngIf-->
<div *ngIf="angForm.controls.email.errors?.required">Email is required</div>
<div *ngIf="angForm.controls.email.errors?.email">it's not a valid email</div>
</div>
</div>
See stackblitz

Related

How can I validate my form and save data in my database? angular php mysql

I'm working on an angular project and I want to develop a form, validate it, and save data in my database with php and mysql. I tried to do this but it doesn't work. I got these errors.
Property 'dataService' does not exist on type 'AppComponent'.
'data' is declared but its value is never read.
Parameter 'data' implicitly has an 'any' type.
Property 'router' does not exist on type 'AppComponent'.
'error' is declared but its value is never read.
Parameter 'error' implicitly has an 'any' type.
register.component.html
<h2 class="text-center">Registration</h2>
<div class="row">
<div class="col-md-3">
</div>
<div class="col-md-6 col-md-offset-3">
<div class="jumbotron">
<form [formGroup]="angForm" autocomplete="off" >
<div class="form-group">
<label for="name">Name</label>
<input type="text" name="name" formControlName="name" autocomplete="off" class="form-control input-sm" required minlength="1" maxlength="250" placeholder="Name"
[class.is-invalid]="name.invalid && (name.dirty || name.touched)">
<div *ngIf="name.invalid && (name.dirty || name.touched)" class="invalid-feedback">
<div *ngIf="name.errors?.['required']">
This field is required.
</div>
</div></div>
<div class="form-group">
<label for="email">Email</label>
<input type="email" name="email" formControlName="email" autocomplete="off" required minlength="1" maxlength="250" class="form-control input-sm" placeholder="Email"
[class.is-invalid]="email.invalid && (email.dirty || email.touched)">
<div *ngIf="email.invalid && (email.dirty || email.touched)" class="invalid-feedback">
<div *ngIf="email.errors?.['required']">
This field is required.
</div>
<div *ngIf="!email.errors?.['required'] && email.errors?.['emailValidator']">
Invalid email format.
</div>
</div></div>
<div class="form-group">
<label for="Password">Password</label>
<input type="password" name="Password" formControlName="password" required minlength="15" autocomplete="off" class="form-control input-sm" placeholder="Password"
[class.is-invalid]="password.invalid && (password.dirty || password.touched)">
<button type="button" class="btn btn-outline-secondary" (click)="user.showPassword = !user.showPassword">
<i class="bi" [ngClass]="{'bi-eye-fill': !user.showPassword, 'bi-eye-slash-fill': user.showPassword}"></i>
</button>
<div *ngIf="password.invalid && (password.dirty || password.touched)" class="invalid-feedback">
<div *ngIf="password.errors?.['required']">
This field is required.
</div>
<div *ngIf="password.errors?.['minlength']">
This field must have at least 8 characters.
</div>
</div></div>
<button type="submit" class="btn btn-success" (click)="validate(angForm1)">Register</button>
</form>
</div>
</div>
<div class="col-md-3">
</div>
</div>
register.component.ts
import { Component, OnInit } from '#angular/core';
import { FormGroup, FormControl, FormBuilder, Validators, NgForm, AbstractControl} from
'#angular/forms';
import { first } from 'rxjs/operators';
import { Router } from '#angular/router';
import { ApiService } from '../api.service';
import { emailValidator } from './email-validator.directive';
interface IUser {
name: string;
email: string;
password: string;
}
#Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss'],
})
export class AppComponent implements OnInit {
angForm!: FormGroup;
user: IUser;
constructor() {
this.user = {} as IUser;
}
ngOnInit(): void {
this.angForm = new FormGroup({
name: new FormControl(this.user.name, [
Validators.required
]),
email: new FormControl(this.user.email, [
Validators.required,
EmailValidator,
]),
password: new FormControl(this.user.password, [
Validators.required,
Validators.minLength(8),
]),
});
}
get name() {
return this.angForm.get('name')!;
}
get email() {
return this.angForm.get('email')!;
}
get password() {
return this.angForm.get('password')!;
}
public validate(angForm1:any): void {
if (this.angForm.invalid) {
for (const control of Object.keys(this.angForm.controls)) {
this.angForm.controls[control].markAsTouched();
}
return;
}
else{ this.dataService. userregistration(angForm1.value.name,angForm1.value.email,
angForm1.value.password).pipe(first()).subscribe(
data => {
this.router.navigate(['login']);
},
error => {
});
}
this.user = this.angForm.value;
console.info('Name:', this.user.name);
console.info('Email:', this.user.email);
console.info('Password:', this.user.password);
}
}
register.php
<?php
include_once "database.php";
$postdata = file_get_contents("php://input");
if (isset($postdata) && !empty($postdata)) {
$request = json_decode($postdata);
$name = trim($request->name);
$pwd = mysqli_real_escape_string($mysqli, trim($request->pwd));
$email = mysqli_real_escape_string($mysqli, trim($request->email));
$sql = "INSERT INTO users(name,password,email) VALUES ('$name','$pwd','$email')";
if ($mysqli->query($sql) === true) {
$authdata = [
"name" => $name,
"pwd" => "",
"email" => $email,
"Id" => mysqli_insert_id($mysqli),
];
echo json_encode($authdata);
}
}
?>
api.service.ts
import {
Injectable,
Output,
EventEmitter
}
from '#angular/core';
import {
map
}
from 'rxjs/operators';
import {
HttpClient
}
from '#angular/common/http';
import {
Users
}
from './users';
#Injectable({
providedIn: 'root'
})
export class ApiService {
redirectUrl: string;
baseUrl: string = "http://localhost/angular_admin/php";
#Output() getLoggedInName: EventEmitter < any > = new EventEmitter();
constructor(private httpClient: HttpClient) {}
public userlogin(username: any, password: any) {
alert(username)
return this.httpClient.post < any > (this.baseUrl + '/login.php', {
username,
password
})
.pipe(map(Users => {
this.setToken(Users[0].name);
this.getLoggedInName.emit(true);
return Users;
}));
}
public userregistration(name: any, email: any, pwd: any) {
return this.httpClient.post < any > (this.baseUrl + '/register.php', {
name,
email,
pwd
})
.pipe(map(Users => {
return Users;
}));
}
//token
setToken(token: string) {
localStorage.setItem('token', token);
}
getToken() {
return localStorage.getItem('token');
}
deleteToken() {
localStorage.removeItem('token');
}
isLoggedIn() {
const usertoken = this.getToken();
if (usertoken != null) {
return true
}
return false;
}
}
In your constructor in your ts:
constructor(private router: Router,private apiservice: ApiService) {
this.user = {} as IUser;
}
public validate(angForm1:any): void {
if (this.angForm.invalid) {
for (const control of Object.keys(this.angForm.controls)) {
this.angForm.controls[control].markAsTouched();
}
return;
}
else{ this.apiservice. userregistration(angForm1.value.name,angForm1.value.email,
angForm1.value.password).pipe(first()).subscribe(
(data: any) => {
this.router.navigate(['login']);
},
error => {
});
}
this.user = this.angForm.value;
console.info('Name:', this.user.name);
console.info('Email:', this.user.email);
console.info('Password:', this.user.password);
}
In your html:
<h2 class="text-center">Registration</h2>
<div class="row">
<div class="col-md-3">
</div>
<div class="col-md-6 col-md-offset-3">
<div class="jumbotron">
<form [formGroup]="angForm" autocomplete="off" >
<div class="form-group">
<label for="name">Name</label>
<input type="text" name="name" formControlName="name" autocomplete="off" class="form-control input-sm" required minlength="1" maxlength="250" placeholder="Name"
[class.is-invalid]="angForm.controls['name'].invalid && (angForm.controls['name'].dirty || angForm.controls['name'].touched)">
<div *ngIf="angForm.controls['name'].invalid && (angForm.controls['name'].dirty || angForm.controls['name'].touched)" class="invalid-feedback">
<div *ngIf="angForm.controls['name'].errors?.required">
This field is required.
</div>
</div></div>
<div class="form-group">
<label for="email">Email</label>
<input type="email" name="email" formControlName="email" autocomplete="off" required minlength="1" maxlength="250" class="form-control input-sm" placeholder="Email"
[class.is-invalid]="angForm.controls['email'].invalid && (angForm.controls['email'].dirty || angForm.controls['email'].touched)">
<div *ngIf="angForm.controls['email'].invalid && (angForm.controls['email'].dirty || angForm.controls['email'].touched)" class="invalid-feedback">
<div *ngIf="angForm.controls['email'].errors.required">
This field is required.
</div>
<div *ngIf="!email.errors?.['required'] && email.errors?.['emailValidator']">
Invalid email format.
</div>
</div></div>
<div class="form-group">
<label for="Password">Password</label>
<input type="password" name="Password" formControlName="password" required minlength="15" autocomplete="off" class="form-control input-sm" placeholder="Password"
[class.is-invalid]="angForm.controls['password'].invalid && (angForm.controls['password'].dirty || angForm.controls['password'].touched)">
<button type="button" class="btn btn-outline-secondary" (click)="user.showPassword = !user.showPassword">
<i class="bi" [ngClass]="{'bi-eye-fill': !user.showPassword, 'bi-eye-slash-fill': user.showPassword}"></i>
</button>
<div *ngIf="angForm.controls['password'].invalid && (angForm.controls['password'].dirty || angForm.controls['password'].touched)" class="invalid-feedback">
<div *ngIf="angForm.controls['password'].errors.required">
This field is required.
</div>
<div *ngIf="angForm.controls['password'].errors.minlength">
This field must have at least 8 characters.
</div>
</div></div>
<button type="submit" class="btn btn-success" (click)="validate(angForm1)">Register</button>
</form>
</div>
</div>
<div class="col-md-3">
</div>
</div>

How can I add a date to an object in Angular?

am sending an put request based on these files.
Venue.ts file
export class Venue {
id: number;
venueName: string;
cityName: string;
emailContact: string;
fighter1: string;
fighter2: string;
dateOfFight: Date;
active: boolean;
}
My Angular Component files:
create-venue.component.html
<h3>Create Event</h3>
<div [hidden]="submitted" style="width: 400px;">
<form (ngSubmit)="onSubmit()">
<div class="form-group">
<label for="name">Venue Name</label>
<input type="text" class="form-control" id="venueName" required [(ngModel)]="venue.venueName" name="venueName">
</div>
<div class="form-group">
<label for="name">City Name</label>
<input type="text" class="form-control" id="cityName" required [(ngModel)]="venue.cityName" name="cityName">
</div>
<div class="form-group">
<label for="name">Email Contact</label>
<input type="text" class="form-control" id="emailContact" required [(ngModel)]="venue.emailContact" name="emailContact">
</div>
<div class="form-group">
<label for="name">Fighter 1 Contact</label>
<input type="text" class="form-control" id="fighter1" required [(ngModel)]="venue.fighter1" name="fighter1">
</div>
<div class="form-group">
<label for="name">Fighter 2 Contact</label>
<input type="text" class="form-control" id="fighter2" required [(ngModel)]="venue.fighter2" name="fighter2">
</div>
<div class="form-group">
<label for="name">Choose a time for your Event:</label>
<input type="datetime-local" class="form-control" id="dateOfFight" min="2021-01-01T00:00" max="2023-06-14T00:00" required [(ngModel)]="venue.dateOfFight" name="dateOfFight">
</div>
<button type="submit" class="btn btn-success">Submit</button>
</form>
</div>
<div [hidden]="!submitted">
<h4>You submitted successfully!</h4>
<!-- <button class="btn btn-success" (click)="newVenue()">Add</button> -->
</div>
create-venue.component.ts
import { VenueService } from '../venue.service';
import { Venue} from '../venue';
import { Component, OnInit } from '#angular/core';
import { Router } from '#angular/router';
#Component({
selector: 'app-create-venue',
templateUrl: './create-venue.component.html',
styleUrls: ['./create-venue.component.css']
})
export class CreateVenueComponent implements OnInit {
venue: Venue = new Venue();
submitted = false;
constructor(private venueService: VenueService,
private router: Router) {}
ngOnInit() {
}
newVenue(): void {
this.submitted = false;
this.venue = new Venue();
}
save() {
this.venueService.createVenue(this.venue)
.subscribe(data => console.log(data), error => console.log(error));
this.venue = new Venue();
this.gotoList();
}
onSubmit() {
this.submitted = true;
this.save();
}
gotoList() {
this.router.navigate(['/venues']);
}
}
My current sent data in chrome:
I am quite new to javascript and angular, maybe this was answered before but I have no idea how to get the input data into the Venue object...
Edit:
This is my header tab:
I
using a string instead of Date type for the dateOfFight property will let you post to the backend without issue.
You can then generate the date with new Date(datestring) on your server if needed. On the front end you can look into date pipes which will help you format the string accordingly.
You also seem to not be capturing any values in your date input. Notice venue.dateOfFight is not even there. Perhaps try logging out your data before posting
You can use a string instead of date type dateOfFight: string;, and before saving, trasform it into a date format with Moment js.
moment(Date.now()).format('YYYY-MM-DD').toString()

Cannot read property of custom Validator and required - Angular

I'm try to make custom Validators that give user message when he/she leave a space on text but i received this error.
1-Cannot read property 'removeSpaceFromUserName' of undefined
2-Cannot read property 'required' of null
at Object.eval [as updateDirectives]
Here's the html of the component
<form [formGroup]='form'>
<div class="form-group">
<label for="username">Username</label>
<input
formControlName='username'
id="username"
type="text"
class="form-control">
<div *ngIf="username.touched && username.touched" class="alert alert-danger">
<div *ngIf="username.errors.required"> You need to enter user name</div>
<div *ngIf="username.errors.minlength"> Min Length is
{{ username.errors.minLength.requiredLength}}
</div>
<div *ngIf="UserNameValiditors.removeSpaceFromUserName">
removeSpaceFromUserName </div>
</div>
</div>
<div class="form-group">
<label for="password">Password</label>
<input
formControlName='password'
id="password"
type="text"
class="form-control">
</div>
<button class="btn btn-primary" type="submit">Sign Up</button>
</form>
Here's the custom validator class
import { AbstractControl, ValidationErrors } from "#angular/forms";
export class UserNameValiditors {
static removeSpaceFromUserName(control: AbstractControl): ValidationErrors | null {
if ((control.value as string).indexOf(' ') >= 0) {
return {
removeSpaceFromUserName: true
};
}
else {
return null;
}
}
}
import { Component } from '#angular/core';
import { FormControl , FormGroup , Validators } from "#angular/forms";
import { UserNameValiditors } from './UserNameValditors';
#Component({
selector: 'signup-form',
templateUrl: './signup-form.component.html',
styleUrls: ['./signup-form.component.css']
})
export class SignupFormComponent {
form= new FormGroup(
{
username : new FormControl('',
[
Validators.required,
Validators.minLength(3) ,
UserNameValiditors.removeSpaceFromUserName
]) ,
password : new FormControl('',Validators.required)
});
get username()
{
return this.form.get('username');
}
}
You can try with this solution.
I have create a demo on Stackblitz
app.component.ts
myForms: FormGroup;
constructor(fb: FormBuilder) {
this.myForms = fb.group({
username: [null, Validators.compose([
Validators.required, Validators.minLength(3), usernameValidator])],
password: [null, [
Validators.required]]
});
}
app.component.html
<form [formGroup]="myForms">
<label>User Name :
<input type="text" formControlName="username">
</label><br>
<div class="errors" *ngIf="myForms.get('username').invalid && (myForms.get('username').touched || myForms.get('username').dirty)">
<div *ngIf="myForms.get('username').hasError('required')">
username is required
</div>
<div *ngIf="myForms.get('username').errors.minlength">
username must be at least 3 characters
</div>
<div class="error-text" *ngIf="myForms.get('username').hasError('removeSpaceFromUserName')">
removeSpaceFromUserName
</div>
</div>
<div class="form-group">
<label for="password">Password</label>
<input
formControlName='password'
id="password"
type="text"
class="form-control">
</div>
<button class="btn btn-primary" type="submit">Sign Up</button>
</form>
Use hasError() to check if certain error is present on the form.
html code
<div *ngIf="username.hasError('required')"> You need to enter user name</div>
<div *ngIf="username.hasError('minlength')"> Min Length is {{ username.hasError('minLength')}}
</div>f
<div *ngIf="username.hasError('removeSpaceFromUserName')">
removeSpaceFromUserName </div>
</div>
Your working code is here

Angular 4 Reactive Forms FormControl errors is null

If I tab through the text inputs without entering anything, the error msg divs display indicating that the required validator has fired correctly. However, if I type anything into one of the fields, the console immediately throws this error:
Cannot read property 'required' of null
Here is my component:
import { PasswordValidators } from './../validators/password.validators';
import { Component, OnInit } from '#angular/core';
import { FormBuilder, Validators, FormGroup, FormControl } from '#angular/forms';
#Component({
selector: 'app-changepassword-form',
templateUrl: './changepassword-form.component.html',
styleUrls: ['./changepassword-form.component.css']
})
export class ChangepasswordFormComponent {
form;
constructor(fb: FormBuilder) {
this.form = fb.group({
newPassword: ['', Validators.required],
confirmPassword: ['', Validators.required]
})
}
get newPassword() {
return this.form.get('newPassword');
}
get confirmPassword() {
return this.form.get('confirmPassword');
}
}
and HTML:
<form [formGroup]="form">
<div class="form-group">
<label for="newPassword">New Password</label>
<input formControlName="newPassword" id="newPassword" type="text" class="form-control">
<div class="alert alert-danger" *ngIf="newPassword.touched && newPassword.errors.required">
Required
</div>
</div>
<div class="form-group">
<label for="confirmPassword">Confirm Password</label>
<input formControlName="confirmPassword" id="confirmPassword" type="text" class="form-control">
<div class="alert alert-danger" *ngIf="confirmPassword.touched && confirmPassword.errors.required">
Required
</div>
</div>
<p><button class="btn btn-primary">Submit</button></p>
</form>
That error is coming from this:
*ngIf="newPassword.touched && newPassword.errors.required"
When you put in a value, there is no longer an errors collection so checking newPassword.errors.required generates that Cannot read property 'required' of null error.
Try something like this instead:
*ngIf="newPassword.touched && newPassword.errors?.required"
As an example, mine looks like this:
<div class="col-md-8">
<input class="form-control"
id="productNameId"
type="text"
placeholder="Name (required)"
required
minlength="3"
[(ngModel)] = product.productName
name="productName"
#productNameVar="ngModel" />
<span class="help-block" *ngIf="(productNameVar.touched ||
productNameVar.dirty || product.id !== 0) &&
productNameVar.errors">
<span *ngIf="productNameVar.errors.required">
Product name is required.
</span>
<span *ngIf="productNameVar.errors.minlength">
Product name must be at least three characters.
</span>
</span>
</div>
You can also use the following syntax and it will work without the need to have a value first:
form.get('newPassword').hasError('required')
This will check for 'required' in the errors.
This will work as well and it's more concise :
form.hasError('required','newPassword')
If you are compiling with AOT option, according to this article, you should privilege hasError() syntax:
Don’t use control.errors?.someError, use control.hasError(‘someError’)

Angular form keep returning false (Angular 2)

I have a form in Angular 2 which I'm validating by the model-driven way. I wanna know how do I change the status from false to true, because I have the rules of validation and even if the user fills everything right, it keeps returning me invalid (false). Here's the HTML code.
<div class="wrap-page">
<form [formGroup]="myForm" novalidate class="form-contato" (ngSubmit)="enviarMensagem(myForm.value, myForm.valid)">
<div class=row>
<div class="col s12">
<h4> Contato </h4>
</div>
<div class="col s12 m12 l6">
<label> Nome: </label>
<input type="text" name="nome" formControlName="nome" class="forms-econ" required placeholder="ex: José Silva">
<div class="div-validar">
<span [hidden]="myForm.controls.nome.valid || (myForm.controls.nome.pristine && !submitted)">
Nome Inválido (mínimo 3 caracteres).
</span>
</div>
</div>
<div class="col s12 l6">
<label> E-mail: </label>
<input type="email" class="forms-econ" formControlName="email" required name="email" pattern="^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$"
placeholder="exemplo#exemplo.com">
<div class="div-validar">
<span [hidden]="myForm.controls.email.valid || (myForm.controls.email.pristine && !submitted)">
E-Mail inválido
</span>
</div>
</div>
<div class="col s12 l6">
<label>Telefone: </label>
<input type="tel" class="forms-econ" name="telefone" formControlName="telefone" pattern="[0-9]" placeholder="(xx)9 9999-99999">
</div>
<div class="col s12 l6">
<label> Motivo do Contato: </label>
<select name="assunto" formControlName="assunto" class="forms-econ">
<option value="motivo_01">Motivo 01</option>
<option value="motivo_02">Motivo 02</option>
<option value="motivo_03">Motivo 03</option>
<option value="motivo_03">Motivo 04</option>
</select>
</div>
<div class="col s12">
<label> Mensagem: </label>
<textarea name="mensagem" formControlName="mensagem" placeholder="Mensagem..." rows="15">
</textarea>
<div class="div-validar">
<span [hidden]="myForm.controls.mensagem.valid || (myForm.controls.mensagem.pristine && !submitted)">
O campo mensagem é obrigatório
</span>
</div>
</div>
<div class="col s12">
<label> ID: </label>
<textarea name="id" formControlName="id" placeholder="Mensagem..." rows="15">
</textarea>
</div>
<h1> {{myForm.valid | json}} </h1> // <-- Here is where I'm printing the status of the form (always return false)
<div class="col s12 right-align">
<input type="submit" value="Enviar" class="btn-form">
</div>
</div>
</form>
</div>
And here is the component.
import { Component, Input } from '#angular/core';
import {FormGroup, FormControl, FormBuilder, Validators} from '#angular/forms';
import {formContato} from './contato.interface';
import {ContatoService} from './contato.service';
#Component({
moduleId: module.id,
selector: 'contato',
templateUrl: `contato.component.html`,
providers: [ContatoService]
})
export class ContatoComponent {
public contato:formContato;
public myForm: FormGroup;
public submitted: boolean;
public events: any[] = [];
constructor(private _fb: FormBuilder, private mensagemContato:ContatoService) { }
ngOnInit() {
this.myForm = this._fb.group({
nome: ['', [<any>Validators.required, <any>Validators.minLength(3)]],
email: ['', <any>Validators.required],
telefone: ['', <any>Validators.required],
assunto: ['', <any>Validators.required],
mensagem: ['', <any>Validators.required],
id: ['']
})
}
enviarMensagem(model: formContato, isValid: boolean) {
this.submitted = true;
console.log(model, isValid); // -< another way to print the status of the form (always false)
}
}
Thanks in advance :)
Your problem is with the e-mail and phone validation. They always validate as false.
Since you are using a reactive form, I would suggest you move your pattern checks to your build of the form, e.g:
email: ['', [<any>Validators.required, Validators.pattern(....)]],
Then I would assume that you want to inform right from the beginning that fields are required. This can be done in quite a few ways, here I show two possible solutions:
<span *ngIf="myForm.get('nome').hasError('required')">
Name required!
</span><br>
or:
<span *ngIf="!myForm.controls.nome.pristine">
Name required!
</span><br>
and as mentioned in other answer, you need not to pass the myForm.valid in the submit.
I made a Plunker for you, where I set another e-mail validation:
EMAIL_REGEXP = '^[a-z0-9]+(\.[_a-z0-9]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,15})$';
and just a random phone number validation, since I wasn't sure exactly what kind of number validation you need. This one checks that the phone number only contains numbers.
If you want you could also disable the submit button if the form is not valid:
<input [disabled]="!myForm.valid" type="submit" value="Enviar" class="btn-form">
but that is of course up to you! :)
Hope this helps!
In Angular 2 , its not required to pass the valid entity on (ngSubmit) , just pass the required form name give to the form group directive .
(ngSubmit)="enviarMensagem(myForm)"
enviarMensagem({model, valid }: {model: Object, valid: boolean}) {
this.submitted = true;
console.log(model, valid);
}

Categories