2

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
  • 1
    use pattern attribute with regex value of /^\S*$/ Commented Jul 16, 2021 at 6:33

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

2 Comments

Any other solution available?
Sure - there are quite a number of options, but I would recommend the above for angular. You could do some other operations on blur/keyup that could perhaps automatically remove spaces - depends on what you want to achieve.

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.