Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to validate white spaces/empty spaces? [Angular 2]

I would like to avoid white spaces/empty spaces in my angular 2 form? Is it possible? How can this be done?

like image 435
Eusthace Avatar asked Aug 30 '16 20:08

Eusthace


People also ask

How do you validate white spaces and empty spaces?

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. and then in your component typescript file use the validator like this for example.

How do you use a validator pattern?

Pattern Validation with ngModel Suppose we have a regex to validate username as given below. unamePattern = "^[a-z0-9_-]{8,15}$"; To perform validation with ngModel , we will use pattern attribute in following way. Now display validation error message.

What are the validations using in angular?

Angular uses directives to match these attributes with validator functions in the framework. Every time the value of a form control changes, Angular runs validation and generates either a list of validation errors that results in an INVALID status, or null, which results in a VALID status.


2 Answers

You can create a custom validator to handle this.

new FormControl(field.fieldValue || '', [Validators.required, this.noWhitespaceValidator]) 

Add noWhitespaceValidator method to your component

public noWhitespaceValidator(control: FormControl) {     const isWhitespace = (control.value || '').trim().length === 0;     const isValid = !isWhitespace;     return isValid ? null : { 'whitespace': true }; } 

and in the HTML

<div *ngIf="yourForm.hasError('whitespace')">Please enter valid data</div> 
like image 90
Praveen M P Avatar answered Sep 18 '22 06:09

Praveen M P


I think a simple and clean solution is to use pattern validation.

The following pattern will allow a string that starts with white spaces and will not allow a string containing only white spaces:

/^(\s+\S+\s*)*(?!\s).*$/ 

It can be set when adding the validators for the corresponding control of the form group:

const form = this.formBuilder.group({             name: ['', [                 Validators.required,                 Validators.pattern(/^(\s+\S+\s*)*(?!\s).*$/)             ]]         }); 
like image 30
Camellia Nacheva Avatar answered Sep 18 '22 06:09

Camellia Nacheva