2016-12-20 29 views
0

我只是問一些關於驗證使用模式的角度2.使空間驗證程序Angular2

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> 

回答

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

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

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

或者你也可以創建一個指令,不允許你鍵入空格。

希望這有助於

+0

的功能幾乎是正確的,但你的函數被反轉,你的功能給我驗證的文本框必須具有的空間,但我想是我的文本框不能輸入空格。 –

+0

Jep,你說得對。我改變了,謝謝。我沒有測試代碼。如果這對你有幫助,請將其標記爲已接受的答案。 – LanderV

+0

我無法修復。請更正此代碼。之後,我將標記此 –

2

如果你想創建一個指令,它消除了對模糊空的空間,你可以使用下面的指令。

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

希望這helps.Thank你