How to add blank space validation in template driven form in angular

Viewed 394

Here form code available. This form type is template driven form In this form SUBSCRIPTION_ID input available. I need add validation like only blank space not allowed.

<form name="ResgisterData" #resgisterData = "ngForm"  (ngSubmit)="signUp(resgisterData.value)" novalidate>
<label>SUBSCRIPTION_ID</label>
<input type="text" [ngClass]="{ 'alert-danger' : subscriptionId.touched && subscriptionId?.errors?.required }" role="textbox" name="Guid" #subscriptionId="ngModel" [(ngModel)]="attendeLabDetails.SubscriptionGuid" autocomplete="off"  class="form-control" required />
<button role="button" class="btn btn-primary blue" [disabled]="resgisterData.invalid">Register </button>
</form>
1 Answers

Steps

Refer to angular docs:

You could create a validator directive.

  1. Use ng generate to generate a new directive called WhiteSpaceValidator
  2. After you've done this implement the validator interface in your directive: Validator
  3. Add the code to check for whitespaces
  4. Add directive to your input

Validator File

@Directive({
  selector: '[whiteSpaceValidator]',
  providers: [{provide: NG_VALIDATORS, useExisting: WhiteSpaceValidatorDirective, multi: true}]
})
class WhiteSpaceValidatorDirectiveimplements Validator {
  validate(control: AbstractControl): ValidationErrors|null {
    /*
    Your validation code here.
    */
    return {'whiteSpace': true};

  }
}

Your subscriptionId?.errors will then have the property 'whiteSpace': true

Related