简体   繁体   English

如何在 angular 的模板驱动表单中添加空格验证

[英]How to add blank space validation in template driven form in angular

Here form code available.这里表单代码可用。 This form type is template driven form In this form SUBSCRIPTION_ID input available.此表单类型是模板驱动的表单 在此表单中 SUBSCRIPTION_ID 输入可用。 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>

Steps脚步

Refer to angular docs :请参阅角度文档

You could create a validator directive.您可以创建一个验证器指令。

  1. Use ng generate to generate a new directive called WhiteSpaceValidator使用ng generate生成一个名为WhiteSpaceValidator的新指令
  2. After you've done this implement the validator interface in your directive: Validator完成此操作后,在指令中实现验证器接口: 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您的subscriptionId?.errors将具有属性'whiteSpace': true

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM