在Angular2中创建空间验证器

时间:2016-12-20 08:49:21

标签: angular

我只想问一下角度2中的验证使用模式。

enter image description here

此图显示了我的页面。在红色框中,我想设置验证。 我的验证是这个文本框无法输入空间并进行修剪。只是简单但我不能这样做。

ngOnInit() {
    this.submitButtonText = 'Save';
    this.form = this.fb.group({
        'id': [],
        'parent': ['-1', Validators.compose([Validators.required])],
        'name': ['', Validators.compose([Validators.required])],
        'title': ['', Validators.compose([Validators.required])],
        'router': ['/apps'],
        'description': ['', Validators.compose([Validators.required])]
    });
    this.parent = this.form.controls['parent'];
    this.name = this.form.controls['name'];
    this.title = this.form.controls['title'];
    this.router = this.form.controls['router'];
    this.description = this.form.controls['description'];
    this.toggleFormControl("router",false);

    this.service.getParent()
        .subscribe(
            data => this.setParent(data['menu']),
            err => this.logError(err),
            () => this.finishedGetIndexList('Save')
        );
    this.statusForm = 'Add';
    if (this.id) {
        this.fetchData();
    }
}

HTML

<div class="form-group row" [ngClass]="{'has-error': (!name.valid && name.touched), 'has-success': (name.valid && name.touched)}">
  <label class="col-sm-2 control-label">Name</label>
  <div class="col-sm-10">
    <input [formControl]="name" type="text" class="form-control" placeholder="name"/>
  </div>
</div>

2 个答案:

答案 0 :(得分:3)

如果您想创建一个删除模糊空白空间的指令,您可以使用下面的指令。

@Directive({
 selector: 'input[type=text]'
 })
export class TrTextTrimDirective {

 constructor(private el: ElementRef, private control: NgControl) {

 }

 @HostListener('blur', ['$event.target.value'])
 onblur(updatedValue: string) {
  let value: any = this.control.control.value;
  if (value != null && typeof value === 'string') {
  value = value.trim();
  this.control.control.setValue(value);
 }
 }
}

希望这会有所帮助。谢谢你

答案 1 :(得分:1)

当输入无效时,Angular2会生成类。您可以使用它们来显示红色轮廓:

input.ng-invalid.ng-dirty {
  outline: 2px solid red;
}

为了验证,您只需添加自己的验证器:

nospaceValidator(control: AbstractControl): { [s: string]: boolean } {
  let re = / /;
  if (control.value && control.value.match(re)) {
    return { nospace: true };
  }
}

然后使用它

'name': ['', Validators.compose([Validators.required, nospaceValidator])],

顺便说一下,在设置多个验证器时只需要Validators.compose。

最后,如果要自动修剪值或自动从新值中删除空格,可以使用FormControl的valueChanges observable

this.name = this.form.controls['name'];

this.name.valueChanges.subscribe((value: string) => {
  console.log('checking value: ', value);
  //do your stuff here
});

或者您也可以创建一个不允许您键入空格的指令。

希望这有帮助