-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?

1
  • See this link. It's a tutorial found on Internet. Commented Dec 18, 2020 at 6:01

3 Answers 3

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.*/;
Sign up to request clarification or add additional context in comments.

Comments

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
   }
  };
};

1 Comment

can you also place an answer just for formcontrol? thanks, and I can send points
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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.