I would like to avoid white spaces/empty spaces in my angular 2 form? Is it possible? How can this be done?
If you are using Angular Reactive Forms you can create a file with a function - a validator. This will not allow only spaces to be entered.
import { AbstractControl } from '@angular/forms';
export function removeSpaces(control: AbstractControl) {
if (control && control.value && !control.value.replace(/\s/g, '').length) {
control.setValue('');
}
return null;
}
and then in your component typescript file use the validator like this for example.
this.formGroup = this.fb.group({
name: [null, [Validators.required, removeSpaces]]
});
What I did was created a validator that did the samething as angular for minLength except I added the trim()
import { Injectable } from '@angular/core';
import { AbstractControl, ValidatorFn, Validators } from '@angular/forms';
@Injectable()
export class ValidatorHelper {
///This is the guts of Angulars minLength, added a trim for the validation
static minLength(minLength: number): ValidatorFn {
return (control: AbstractControl): { [key: string]: any } => {
if (ValidatorHelper.isPresent(Validators.required(control))) {
return null;
}
const v: string = control.value ? control.value : '';
return v.trim().length < minLength ?
{ 'minlength': { 'requiredLength': minLength, 'actualLength': v.trim().length } } :
null;
};
}
static isPresent(obj: any): boolean {
return obj !== undefined && obj !== null;
}
}
I then in my app.component.ts overrode the minLength function provided by angular.
import { Component, OnInit } from '@angular/core';
import { ValidatorHelper } from 'app/common/components/validators/validator-helper';
import { Validators } from '@angular/forms';
@Component({
selector: 'app-root',
templateUrl: './app.component.html'
})
export class AppComponent implements OnInit {
constructor() { }
ngOnInit(): void {
Validators.minLength = ValidatorHelper.minLength;
}
}
Now everywhere angular's minLength built in validator is used, it will use the minLength that you have created in the helper.
Validators.compose([
Validators.minLength(2)
]);
export function noWhitespaceValidator(control: FormControl) {
const isSpace = (control.value || '').match(/\s/g);
return isSpace ? {'whitespace': true} : null;
}
to use
password: ['', [Validators.required, noWhitespaceValidator]]
In template/html
<span *ngIf="newWpForm.get('password').hasError('whitespace')">
password cannot contain whitespace
</span>
I had a requirement where in the Firstname and Lastname are user inputs which were required fields and user should not be able to hit space as the first character.
Import AbstractControl from node_modules.
import { AbstractControl } from '@angular/forms';
check if the first character is space If yes then blank the value and return required: true. If no return null
export function spaceValidator(control: AbstractControl) {
if (control && control.value && !control.value.replace(/\s/g, '').length) {
control.setValue('');
console.log(control.value);
return { required: true }
}
else {
return null;
}
}
the above code will trigger an error if the first character is space and will not allow space to be the first character.
And in form builder group declare
this.paInfoForm = this.formBuilder.group({
paFirstName: ['', [Validators.required, spaceValidator]],
paLastName: ['', [Validators.required, spaceValidator]]
})
In your app.component.html
<form [formGroup]="signupForm">
<input type="text" name="name" [formControl]="signupForm.controls['name']"
placeholder="First Name"
required
/>
<small
*ngIf="signupForm.controls['name'].hasError('pattern')"
class="form-error-msg"
>First Name without space</small>
</form>
In your app.componen.ts file
import { Validators, FormGroup, FormControl } from "@angular/forms";
signupForm: FormGroup;
ngOnInit(){
this.signupForm = new FormGroup({
name: new FormControl("", [
Validators.required,
Validators.pattern("^[a-zA-Z]+$"),
Validators.minLength(3)
])
})
Following directive could be used with Reactive-Forms to trim all form fields so standart Validators.required
work fine:
@Directive({
selector: '[formControl], [formControlName]',
})
export class TrimFormFieldsDirective {
@Input() type: string;
constructor(@Optional() private formControlDir: FormControlDirective,
@Optional() private formControlName: FormControlName) {}
@HostListener('blur')
@HostListener('keydown.enter')
trimValue() {
const control = this.formControlDir?.control || this.formControlName?.control;
if (typeof control.value === 'string' && this.type !== 'password') {
control.setValue(control.value.trim());
}
}
}