Reputation: 197
My aim is to ensure that the user enters valid data (No numbers) and input field should not be empty before the form is submitted. Help!!!
The ts file code as follows:
import { Routes, RouterModule, Router, ActivatedRoute } from "@angular/router";
import { Component, NgModule, Input, Output, EventEmitter } from '@angular/core';
import { Environments } from './Environment-class';
import { FormBuilder, FormsModule, ReactiveFormsModule, FormGroup, FormControl, Validators } from '@angular/forms';
@Component({
selector: 'addenvironment-form',
templateUrl: './add-environment-form.component.html'
})
export class AddEnvironmentComponent {
@Output() EnvironementCreated = new EventEmitter<Environments>();
createNewEnv(EnvironmentNames: string) {
this.EnvironementCreated.emit(new Environments(EnvironmentNames));
}
}
And the HTML file
<br />
<div class="card">
<h4 class="card-header">Add a New Environment</h4>
<div class="card-body mx-auto ">
<form class="form-inline ">
<div class="form-group ">
<h5 class="form-control-static">Enter New Name: </h5>
</div>
<div class="form-group mx-lg-3 text-center">
<label for="inputPassword2" class="sr-only">Password</label>
<input type="text" class="form-control " id="inputPassword4" placeholder=" Name " #EnvironmentNames>
</div>
<button type="submit" class="btn btn-primary" (click)="createNewEnv(EnvironmentNames.value)">Submit</button>
</form>
</div>
Upvotes: 3
Views: 4152
Reputation: 1458
You can add required
tag to input filed so it has to be filled in.
Additionally you can add minlength
.
To make it letters only you can use pattern
. You can play with characters you what to allow user to input.
If you are going to use this input for password, I would suggest you to change type
to type="password"
You can also disable
button if the form is not valid.
With all this mentioned above, your form should look something like bellow:
<form [formGroup]="myForm" class="form-inline ">
<div class="form-group ">
<h5 class="form-control-static">Enter New Name: </h5>
</div>
<div class="form-group mx-lg-3 text-center">
<label for="inputPassword2" class="sr-only">Password</label>
<input type="password" class="form-control " id="inputPassword4"
placeholder=" Name " #EnvironmentNames pattern="^[a-zA-Z]+$"
minlength="8" required>
</div>
<button type="submit" class="btn btn-primary"
(click)="createNewEnv(EnvironmentNames.value)"
[disabled]="!myForm.valid">Submit
</button>
</form>
Upvotes: 5