Form validation not working correctly when user hits login button (Angular 2) - forms

I have a form with username and password, when a user hits the submit button, a error message is displayed stating if one or both fields are blank, I'm trying to add a route to the button so it takes them to the home page, however, when I add a route to the button, it ignores the validation as aspect and will work if fields are blank. I've tried to disable the button so that it's only enabled when the form is valid but I'm getting a bit confused between ngForm and ngFormModel
Thanks
This is my html form
<form [ngFormModel]="loginForm" (ngSubmit)="loginUser(loginForm.value)">
<div class="form-group" [ngClass]="{ 'has-error' : !username.valid && submitAttempt }">
<label class="control-label" for="username">Username</label>
<em *ngIf="!username.valid && submitAttempt">Required</em>
<input id="username" type="text" class="form-control" placeholder="Username" ngControl="username">
</div>
<div class="form-group" [ngClass]="{ 'has-error' : !password.valid && submitAttempt }">
<label class="control-label" for="password">Password</label>
<em *ngIf="password.hasError('required') && submitAttempt">Required</em>
<em *ngIf="password.hasError('minlength') && submitAttempt">Must be at least 8 characters</em>
<input id="password" type="password" class="form-control" placeholder="Password" ngControl="password">
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary">Register</button>
</div>
</form>
And this is my component
import {Component, EventEmitter} from "angular2/core";
import {Router} from "angular2/router";
import {ROUTER_DIRECTIVES} from "angular2/router";
import {Control, ControlGroup, FormBuilder, Validators, FORM_DIRECTIVES} from 'angular2/common';
//import {UsernameValidators} from './usernameValidators';
#Component({
selector: 'LoginHTML',
templateUrl: 'dev/LoginComponents/login-form.component.html',
directives : [FORM_DIRECTIVES]
})
export class LoginHTMLComponent{
loginForm: ControlGroup;
username: Control;
password: Control;
submitAttempt: boolean = false;
form: ControlGroup;
constructor( private builder: FormBuilder, private _router: Router) {
this.username = new Control('', Validators.required)
this.password = new Control('', Validators.compose([Validators.required, Validators.minLength(8)]))
this.loginForm = builder.group({
username: this.username,
password: this.password
});
}
loginUser(user) {
this.submitAttempt = true;
this._router.navigate(['Dashboard']);
}
}

You should be free to do anything with your code, so the form won't try to intervene your loginUser function to navigate to Dashboard. But it does provide you information about form validity that you can make use of:
loginUser(user) {
this.submitAttempt = true;
if (this.loginForm.valid) {
this._router.navigate(['Dashboard']);
}
}

Related

angular 5 form with form builder

I am trying to implement a form in Angular5. But there occurs a error in the console which states 'formGroup needs to have an instance of FormGroup'
This is the HTML code:
<form [formGroup]="userInfo" (ngSubmit)="onSubmit()" novalidate>
<div class="input-section">
<div class="form-group filled-form">
<label for="businessName">What positions are you hiring for?</label>
<input class="form-control myInputStyle" type="text" id="enterEmail"
formControlName="businessname" required>
<div [hidden]="userInfo.controls['businessname'].valid ||
userInfo.controls['businessname'].pristine" class="inline-error">
Please enter a Business name!
</div>
</div>
</div>
</form>
Here is the ts code :
export class HwaPreviewComponent implements OnInit {
public userInfo:FormGroup;
constructor(private router: Router) { }
ngOnInit() {
}
onSubmit() {
if (this.userInfo.valid) {
console.log("Form Submitted!");
}
}
public userInfo:FormGroup; - adding this in the .ts file helped

Angular validation message for maxlength attribute

I'm having some trouble with displaying error messages for the maxlength attribute in Angular.
Problem
Since the maxlength attribute don't allow more characters than the specified amount, I'm having trouble displaying my error message. Is there any way to turn of the default behavior (allow the user to type more characters), in order to display my error message.
Code for textarea
<textarea maxlength="10"
[(ngModel)]="title.value"
#title="ngModel"></textarea>
Code for Angular validation
<div *ngIf="title.errors && (title.dirty || title.touched)"
class="alert alert-danger">
<div [hidden]="!title.errors.maxlength">
Only 10 characters allowed.
</div>
</div>
If you want me to provide any additional information, please let me know.
you can work with Reactive forms to validate properly your form,
here is a simple example how to use reactive forms :
import { Component, OnInit } from '#angular/core';
import { FormBuilder, FormGroup, Validators } from '#angular/forms';
#Component({
selector: 'title-form',
template: `
<form novalidate [formGroup]="myForm">
<label>
<span>Full title</span>
<input type="text" placeholder="title.." formControlName="title">
</label>
<div*ngIf="myForm.controls['title'].touched && myForm.get('title').hasError('required')">
Name is required
</div>
<div *ngIf="myForm.controls['title'].touched && myForm.controls['title'].hasError('maxlength')">
Maximum of 10 characters
</div>
</form>
`
})
export class TitleFormComponent implements OnInit {
myForm: FormGroup;
constructor(private fb: FormBuilder) {}
ngOnInit() {
this.myForm = this.fb.group({
title: ['', [Validators.required, Validators.maxLength(10)]],
});
}
}
hope it helps u :)
You can achieve it by setting the condition directly on the length of the input. A span tag with *ngIf can show/hide the error message:
HTML
<textarea class="form-control" id="title"
type="number" name="title" [(ngModel)]="titleModel"></textarea>
<span style="color:red" *ngIf="titleModel?.length > 10">
10 max
</span>
Class:
...
titleModel = 'I have more than 10 characters'
...
DEMO

Angular 4 form validation

How to validate a form in angular 4 by clicking on external link (ie out side from tag). If the form is valid do some actions with form data else show validation messages. If form is valid I don't want to submit the form just need to get the form field values.
This is my answer post to another question:
The easy way is to use reactive forms, like this:
Code:
import {ReactiveForm, FormBuilder, Validators} from '#angular/form';
export class SignupFormComponent implements OnInit {
userForm: FormGroup;
firstName: string;
constructor(private _formBuilder:FormBuilder){}
ngOnInit() {
this.userForm = this._formBuilder.group({
'firstName': ['',[Validators.required,Validators.minLength(5)]]
});
}
onSubmit() {
console.log(this.firstName);
}
}
HTML:
<form [formGroup]="userForm" (ngSubmit)="onSubmit()" name="userForm">
<div class="form-group">
<label>First Name</label>
<input type="text" [(ngModel)]="firstName" class="form-control" formControlName="firstName">
<p *ngIf="userForm.controls.firstName.invalid && (userForm.controls.firstName.dirty || userForm.controls.firstName.touched)"> Error message </p>
</div>
<button type="submit" class="btn btn-primary" [disabled]="userForm.invalid">Submit </button>
</form>

Can't access the data of the form submitted

I am starting with angular2. I have a simple template driven form and I can access the data in console. But I am having problem with passing the data. Here is my code.
import {Component} from "angular2/core";
#Component({
selector: 'my-template-driven',
template:`
<h2>Sign-up form</h2>
<form (ngSubmit)="onSubmit(f)" #f="ngForm">
<div>
<label for="email">Mail</label>
<input ngControl="email" type="text" id="email" required #email="ngForm">
<span class="validation-error" *ngIf="!email.valid">Not Valid</span>
</div>
<div>
<label for="password">Password</label>
<input ngControl="password" type="text" id="password" required #password="ngForm">
<span class="validation-error" *ngIf="!password.valid">Not Valid</span>
</div>
<div>
<label for="confirm-password">Confirm Password</label>
<input ngControl="confirm-password" type="text" id="confirm-password" required #passwordConfirm="ngForm">
<span class="validation-error" *ngIf="!passwordConfirm.valid">Not Valid</span>
</div>
<button type="submit" [disabled]="!f.valid || password.value !== passwordConfirm.value">Submit</button>
</form>
<h2>You Submitted</h2>
`
})
export class TemplateDrivenFormComponent {
user: {email: '', password: ''};
onSubmit(form){
//console.log(form);
this.user.email = form.value['email'];
//this.user.password = form.controls['password'].value;
}
}
I am getting this angular2.js:23941 ORIGINAL EXCEPTION: TypeError: Cannot set property 'email' of undefined error constantly. How can I access the data of the form submitted.
You don't declare your local correctly, and you must initialize it when you declare it, or in your constructor maybe
user: any;
constructor() {
this.user = {email: "", password: ""} as any;
}
after : you must provide the type.
Html input must have "ngModel" attribute in it.

Set model date defaultValue to string

I try to build a 'task manager' to log the tasks that my customers send me.
I have my new-task.hbs form
<div id="new-task-form" class="col-md-12">
<form>
<div class="form-group">
<label>Customer</label>
{{input type="text" class="form-control" value=customer placeholder="Add Customer..."}}
</div>
<div class="form-group">
<label>Task</label>
{{textarea class="form-control" value=task placeholder="Add Task..."}}
</div>
<div class="form-group">
<label>Incoming</label>
{{input type="number" class="form-control" value=incoming placeholder="Bring it on..."}}
</div>
<div class="form-group">
<label>Pending</label>
{{input type="number" class="form-control" value=pending placeholder="Don't bring it on..."}}
</div>
<div class="form-group">
<label>Closed Date</label>
{{input type="date" class="form-control" value=closed_date placeholder="Please close me..."}}
</div>
<button {{action 'addTask'}} class="btn btn-primary">Submit</button>
</form>
My controller.
import Ember from 'ember';
export default Ember.Controller.extend({
actions: {
addTask: function(){
var customer = this.get('customer');
var task = this.get('task');
var incoming = this.get('incoming');
var pending = this.get('pending');
var closed_date = this.get('closed_date');
//Create new task
var newTask = this.store.createRecord('task',{
customer: customer,
task: task,
incoming: incoming,
pending: pending,
closed_date: closed_date
});
//save to db
newTask.save();
}
}
});
And the model
import Model from 'ember-data/model';
import attr from 'ember-data/attr';
export default Model.extend({
customer: attr('string'),
task: attr('string'),
incoming: attr('number', { defaultValue: 0 }),
pending: attr('number', { defaultValue: 0 }),
closed_date: attr('date'),
created: attr('string', {
defaultValue: function(){
return new Date();
}
})
});
How can i set a model defaultValue for a the closed_date input to a string "Not entered yet"?
If i leave it like this and not enter a value i get an "Invalid Date".
closed_date: attr('date')
If i set this i get the current date.
closed_date: attr('date', { defaultValue: 'Not entered yet' })
From my experience I suggest you leave closed_date as it is (as date) and focus on DISPLAYING Not entered yet in each place that you want to show it when closed_date isn't entered.
For example when you show model values in template you can use:
Closed date: {{if model.closed_date model.closed_date 'Not entered yet'}}
Consider using ember-pikaday for a nice date-selection experience (which also gives you the placeholder functionality you are looking for!).
Furthermore, I'd suggest that you use the model hook of your new-task route to do your model setup. Combine that with ember-data-route to do cleanup on route exit, and you should be good to go:
router.js:
this.route('tasks', function() {
this.route('new');
});
routes/tasks/new.js:
import Ember from 'ember';
import DataRoute from 'ember-data-route';
export default Route.extend(DataRoute, {
model() {
return this.store.createRecord('task');
}
});
Note below how the form field values have been updated to model.fieldName. These values are bound to the model you created in your route's model hook.
templates/tasks/new.hbs:
<div id="new-task-form" class="col-md-12">
<form>
<div class="form-group">
<label>Customer</label>
{{input type="text" class="form-control" value=model.customer placeholder="Add Customer..."}}
</div>
<div class="form-group">
<label>Task</label>
{{textarea class="form-control" value=model.task placeholder="Add Task..."}}
</div>
<div class="form-group">
<label>Incoming</label>
{{input type="number" class="form-control" value=model.incoming placeholder="Bring it on..."}}
</div>
<div class="form-group">
<label>Pending</label>
{{input type="number" class="form-control" value=model.pending placeholder="Don't bring it on..."}}
</div>
<div class="form-group">
<label>
Closed Date:
{{pikaday-input value=model.closedDate placeholder="Please close me..."}}
</label>
</div>
<button {{action 'addTask'}} class="btn btn-primary">Submit</button>
</form>
Note: prefer camelCasedMultipleWordModelAttributeName vs underscored_attribute_name
models/task.js:
import Model from 'ember-data/model';
import attr from 'ember-data/attr';
export default Model.extend({
customer: attr('string'),
task: attr('string'),
incoming: attr('number', { defaultValue: 0 }),
pending: attr('number', { defaultValue: 0 }),
closedDate: attr('date', {
defaultValue() { return new Date(); }
}),
created: attr('string', {
defaultValue() { return new Date(); }
})
});
Now the nice part. Here's what your controller action looks like when you do your setup in your route's model hook:
controllers/tasks/new.js
import Ember from 'ember';
export default Ember.Controller.extend({
actions: {
addTask: function(){
this.get('model').save();
}
}
});
and for extra credit you could install ember-route-action-helper and move the controller action onto the route and remove the controller completely.