Component:
ngOnInit() {
this.record = new FormGroup({
movement: new FormControl(''),
weight: new FormControl('', [Validators.required, Validators.minLength(1), Validators.maxLength(3)]),
date: new FormControl('', [Validators.required]),
comments: new FormControl('', [Validators.required, Validators.minLength(3), Validators.maxLength(25)]),
});
}
View:
<div class="column col-6">
<div class="form-group">
<label class="form-label">Weight</label>
<input formControlName="weight" class="form-input" type="text" placeholder="Weight" />
</div>
</div>
<div class="column col-6">
<div class="form-group">
<label class="form-label">Date</label>
<input formControlName="date" class="form-input" type="text" placeholder="Date" />
</div>
</div>
I've got the above validation working just fine, but I need to change the validators on weight to only accept numerical values and the validators on date to accept a specific format (##/##/####).
I've been searching forever and haven't found any built-in methods of doing this. Does anyone have any suggestions? Thanks!
There are only a small number of built-in form validation rules in Angular.
required
minLength
maxLength
pattern (which you could use for email)
EDIT:
More built in:
min
max
email
nullValidator
requiredTrue
Validators API (thank you, #developer033)
If you want to do anything beyond that, you will have to code your own. They are not difficult.
You can find an example on how to build and use a custom validator at the link below.
Custom validation
If you happen to have a Pluralsight subscription, Deborah Kurata has a great course on Angular Reactive Forms, and there is a clip or two on custom form validation in the Validation module.
Related
I have done a small Web App in Angular 4 and I'm now trying to test it.
Here is what I would like to test :
<form class="navbar-form navbar-left" (ngSubmit)="onSubmit(f)" #f="ngForm">
<div class="form-group">
<input type="text" class="form-control" placeholder="Search" ngModel name="name" pattern=".{2,}" required #name="ngModel">
</div>
<button type="submit" class="btn btn-default" [disabled]="!f.valid">
<span class="glyphicon glyphicon-search" aria-hidden="true"></span>
</button>
<span class="help-block help" *ngIf="!name.valid && name.touched ">Please enter at least two characters</span>
</form>
At first, I would just like to test if the form is really invalid (and then I cannot click on the submit button) if thye word entered in the input is less than 2 characters.
Here is the test code I have written
beforeEach(() => {
fixture = TestBed.createComponent(NavbarComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should disable submit if word<2',()=>{
const compiled = fixture.nativeElement;
const input = fixture.debugElement.query(By.css('input'));
input.nativeElement.value='b';
input.nativeElement.dispatchEvent(new Event('input'));
fixture.detectChanges();
//console.log(compiled.querySelector('input').textContent);
//console.log(compiled.querySelector('.ng-valid'));
expect(compiled.querySelector('.ng-valid')).toBe(null);
});
The textContent of the input is modified properly but the form is still valid. However, when I use the webapplication, I can't submit the form is the word is less than two characters.
I feel like the word in the input doesn't really "reach" the form in the test. I've tried a lot of different things so any help would be great !
I am migrating code from angular beta to RC5 version.
and i am facing issue with the model based forms used.
As i have to much forms already developed in angular 2 beta. its hard for me to changes model based forms to template based forms.
any help in forms migration is highly appreciated.
my existing code is like this
profile.ts
import {FORM_DIRECTIVES, REACTIVE_FORM_DIRECTIVES} from '#angular/forms';
import {FormBuilder, FormGroup, FormControl, Validators} from '#angular/forms';
this.firstName = new FormControl();
this.lastName = new FormControl();
this.email = new FormControl();
this.addressLine = new FormControl();
this.postal = new FormControl();
this.postalArea = new FormControl();
this.form = builder.group({
firstName: this.firstName,
lastName: this.lastName,
email: this.email,
addressLine: this.addressLine,
postal: this.postal,
postalArea: this.postalArea,
photo: this.photo
});
and template in profile.HTML is like follows
<form class="form-default" [formGroup]="form">
<input type="text" class="form-control" id="firstName" [(ngModel)]="model.firstName" formControlName="firstName" maxlength="200">
<input type="text" class="form-control" id="lastName" [(ngModel)]="model.lastName" formControlName="lastName" maxlength="200">
<input type="text" class="form-control" id="email" [(ngModel)]="model.username" readonly formControlName="email" maxlength="100">
</form>
I am facing following error in console.
EXCEPTION: Error: Uncaught (in promise): EXCEPTION: Error in
/assets/scripts/my-profile/my-profile.html:176:66 ORIGINAL EXCEPTION:
ngModel cannot be used to register form controls with a parent formGroup directive. Try using
formGroup's partner directive "formControlName" instead. Example:
<div [formGroup]="myGroup">
<input formControlName="firstName">
</div>
In your class:
this.myGroup = new FormGroup({
firstName: new FormControl()
});
Or, if you'd like to avoid registering this form control, indicate that it's standalone in ngModelOptions:
Example:
<div [formGroup]="myGroup">
<input formControlName="firstName">
<input [(ngModel)]="showMoreControls" [ngModelOptions]="{standalone: true}">
</div>
Here you can find the answer to the same problem just add:
[ngModelOptions]="{standalone: true}"
to have the both ngModel and formControl in your html you have to have a model in your component (e.g. firstName in the following example) that you bind to from your html and also you need to build a form group including your desired formControl (e.g. firstNameControl in the following example)
component:
this.firstName: string;
this.form = builder.group({
firstNameControl: this.firstName,
});
html
<form [formGroup]="form">
<input type="text" [(ngModel)]="firstName" [formControl]="form.controls.firstNameControl"></input>
</form
I'm trying to use ngControl to apply error classes based on user's input.
Somehow, I can't make it to work. I see that appropriate classes are set (line ng-invalid), but when trying to use name.valid (where name is my ngControl) it doesn't work.
html:
<div ngClass="{alert: name.invalid}">
<label for="name">Name</label>
<input ngControl="name" #name id="name" [(ngModel)]="user.name"/>
</div>
</div>
js
export class App {
userForm: any;
user: any;
constructor(
private _formBuilder: FormBuilder) {
this.user = {name: 'Ben'};
this.userForm = this._formBuilder.group({
'name': ['', Validators.required]
});
}
}
I saw on angular.io examples that they do use it like this (just for other cases, like show/hide divs)?
Here's the simple plunker: http://plnkr.co/edit/BKx4yplIOu44tk7Mfolc?p=preview
When input field is empty, I would expect that upper div gets alert class, but that doesn't happen.
In fact there are three things to change in your template:
ngClass should be [ngClass]. Otherwise the value is considered as a string and not as an expression.
#name should be #name="ngForm". Otherwise you reference the DOM element and not the control.
there is no invalid property on controls in Angular2 but only a valid one.
Here is the refactored code:
<div [ngClass]="{alert: !name.valid}">
<label for="name">Name</label>
<input ngControl="name" #name="ngForm"
required id="name" [(ngModel)]="user.name"/>
</div>
Here is the plunkr: http://plnkr.co/edit/OJfb9VDqlrRH4oHXQJyg?p=preview.
Note that you can't leverage of FormBuilder with ngControl since the latter allows you to define inline form. With FormBuilder you must use ngFormControl instead.
Here is a sample:
<div [ngClass]="{alert: !userForm.controls.name.valid}">
<label for="name">Name</label>
<input [ngFormControl]="userForm.controls.name"
id="name" [(ngModel)]="user.name"/>
</div>
See this article for more details:
http://restlet.com/blog/2016/02/11/implementing-angular2-forms-beyond-basics-part-1/
I'm a beginner in the AngularJs and MongoDb world (i started learning today!!)
Actually i'm trying to do something very basic : Display a list of record, with an add button and a edit link with each record.
I'm using this lib https://github.com/pkozlowski-opensource/angularjs-mongolab to connect to mongoweb.
Actually my data is displayed, when i try to add a record it works, but the problem is when i try to display the edit form!
Here is my index.html file, in which i display the data with a form to add a record and with the edit links :
<div ng-controller="AppCtrl">
<ul>
<li ng-repeat="team in teams">
{{team.name}}
{{team.description}}
edit
</li>
</ul>
<form ng-submit="addTeam()">
<input type="text" ng-model="team.name" size="30" placeholder="add new team here">
<input type="text" ng-model="team.description" size="30" placeholder="add new team here">
<input class="btn-primary" type="submit" value="add">
</form>
</div>
And here is my edit.html code, which displays an edit form :
<div ng-controller="EditCtrl">
<form ng-submit="editTeam()">
<input type="text" name="name" ng-model="team.name" size="30" placeholder="edit team here">
<input type="text" name="description" ng-model="team.description" size="30" placeholder="edit team here">
<input class="btn-primary" type="submit" value="validate edit">
</form>
</div>
And finally my js code:
var app = angular.module('app', ['mongolabResource']);
app.constant('API_KEY', '____________________________');
app.constant('DB_NAME', 'groups');
app.factory('Teams', function ($mongolabResource) {
return $mongolabResource('teams');
});
app.controller('AppCtrl', function ($scope, Teams) {
$scope.teams = Teams.query();
$scope.addTeam = function() {
varteam = {
name: $scope.team.name,
description: $scope.team.description
};
$scope.teams.push(varteam);
Teams.save($scope.team);
$scope.team.name = '';
$scope.team.description = '';
};
});
app.controller('EditCtrl', function ($scope, Teams) {
//????????
});
My AppCtrl works perfecty, it displays the data w add records perfectly.
Now i want to add the js code for the edit, but i don't even know form where to start ? how do i a get the id parameter in the url ? how do i tell the view to fill out the form fields from the values from the database ? And finally how do i update the databse.
I know that i asked a lot of question but i'm really lost! thank you
There are of course many possible solutions.
One solution is to use angularjs routing. See http://docs.angularjs.org/tutorial/step_07 for a tutorial.
Basically replace your ul list with something like:
<ul>
<li ng-repeat="team in teams">
{{team.name}}
{{team.description}}
edit
</li>
</ul>
Then you can create a route that responde to your url:
yourApp.config(['$routeProvider',
function($routeProvider) {
$routeProvider.
when('/teams', {
templateUrl: 'partials/team-list.html',
controller: 'TeamListCtrl'
}).
when('/teams/:teamId', {
templateUrl: 'partials/team-detail.html',
controller: 'TeamDetailCtrl'
}).
otherwise({
redirectTo: '/teams'
});
}]);
In this way from the detail controller (that will replace your EditCtrl) you can access the id parameter using: $routeParams.teamId
Anyway I suggest to study well all the tutorials for a better overview.
New to Meteor. I have a form with several fields
<template name="addcityform">
<form name="addcity">
<input name="city" class="city" type="text">
<input name="population" class="population" type="text">
<input type="Submit" value="Add City">
</form>
</template>
I just want to insert the fields into the database, but I'm stumped on how to do it. Here's what I currently have after several attempts:
Template.addcityform.events({
'submit .addcity' : function(evt, template) {
Cities.insert({
city: template.find('input.city').value,
population: template.find('input.population').value
});
}
});
// this gives: Uncaught TypeError: Cannot read property 'value' of null
I saw some examples that use Session.set and document.getElementById, but that seems clumsy to me due to the potential for namespace conflicts. I'd like to do this the 'right way' so that it's extensible later, for example, I could put multiple instances of the form onto the page and they should be independent of each other. What is the 'right way' to do this?
You lack an event.preventDefault() in the "submit form" handler, or else the page will reload and ruin the single-page app experience of Meteor.
I would do something like :
<template name="addcityform">
<form>
<input name="city" class="city" type="text">
<input name="population" class="population" type="text">
<button type="submit">Add City</button>
</form>
</template>
Template.addcityform.events({
"submit form": function(event, template) {
event.preventDefault();
Cities.insert({
city: template.find(".city").value,
population: template.find(".population").value
});
}
});
What's cool about Meteor templates is that css selectors used within them are local to the current template, meaning that "submit form" will always refer to "submit event of the form element in enclosing template", given that you only have one form in the template.
The same applies to template instances .find method : it will return an element matching the css selector within the template or its sub-templates.
This allows you to have multiple instances of your addcityform that will be independent from each other.