-1

I used formcontrol in Angular2 and want to add validation pattern for not to allow No "spaces" at all in input. How can this be done?

Similar question: How to add Validation pattern not to allow only space in input Angular2?

  • [See this link](https://www.itsolutionstuff.com/post/angular-form-validation-no-whitespace-allowed-exampleexample.html). It's a tutorial found on Internet. – antoineso Dec 18 '20 at 06:01

3 Answers3

2

You can add a regex pattern in your input field to not to include spaces. I have used no space validation on password input field in my Angular App. Please have a look.

HTML

<input
 type="password"
 class="pass"
 ngModel
 placeholder="Password"
 [pattern]="noSpacesRegex"
 name="password"
 matInput
 required
 #passwordInput="ngModel"
/>

Regex variable:

const noSpacesRegex = /.*\S.*/;
1
 formInitialization() {
    this.forbiddenRules = FORBIDDEN_WORD_RULE();
    this.forbiddenWordForm = this.fb.group({
      'forbiddenWordName': ['', [
        Validators.required,
        Validators.pattern(this.forbiddenRules.FORBIDDEN_WORD_PATTERN),
        Validators.minLength(this.forbiddenRules.MIN_LENGTH), Validators.maxLength(this.forbiddenRules.MAX_LENGTH)]],
      
        'forbiddenWordReplaceWord': ['', [
          Validators.required,
          Validators.pattern(this.forbiddenRules.FORBIDDEN_WORD_PATTERN),
          Validators.minLength(this.forbiddenRules.MIN_LENGTH), Validators.maxLength(this.forbiddenRules.MAX_LENGTH)]],

      'action':  ['', [Validators.required]],
      'forbiddenWordStatus': [this.forbiddenWordStatus === 'Active' ? true : false],
    });
  }

export const FORBIDDEN_WORD_RULE = () => {
  return {
  'FORBIDDEN_WORD_PATTERN': `[${getUniCode()}&,-]+(\\s[${getUniCode()}&,-]+){0,}?`,
  'KEYPRESS_FORBIDDEN_GROUP': `/^[${getUniCode()}&,_\- ]+$/`,
  'MIN_LENGTH': 2,
  'MAX_LENGTH': 50,
  'RESOLUTION': {
    'RESOLUTION_WIDTH': 0,
    'RESOLUTION_HEIGHT': 0
   }
  };
};
Darshan Malani
  • 478
  • 3
  • 12
0

All answers before are correct . You can make a custom validator and use it in a formcontrol. first create a file name for exemple : custom.validator.ts that you can add into a folder name validators

import { AbstractControl, ValidationErrors } from '@angular/forms';
  
export class CustomValidator {
    static cannotContainSpace(control: AbstractControl) : ValidationErrors | null {
        if((control.value as string).indexOf(' ') >= 0){
            return {cannotContainSpace: true}
        }
  
        return null;
    }
}

In your Component .ts file where is you're form you can do something like this :

import { Component } from '@angular/core';
import { FormGroup, FormControl, Validators} from '@angular/forms';
import {CustomValidator } from './validators/custom.validator';
  
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  form = new FormGroup({
    username: new FormControl('', [Validators.required,CustomValidator.cannotContainSpace]),
   
  });
   
  get f(){
    return this.form.controls;
  }
    
  submit(){
    console.log(this.form.value);
  }
}

And finally in the html template :

<form [formGroup]="form" (ngSubmit)="submit()">
   
    <div class="form-group">
        <label for="username">Username</label>
        <input 
            formControlName="username"
            id="username" 
            type="text" 
            class="form-control">
        <div *ngIf="f.username.touched && f.username.invalid" class="alert alert-danger">
           
            <div *ngIf="f.username.errors.cannotContainSpace">Username can not contain space.</div>
        </div>
    </div>
    
    
    <button class="btn btn-primary" type="submit">Submit</button>
</form>

antoineso
  • 2,063
  • 1
  • 5
  • 13