2016-08-30 51 views
4

我想避免在我的角2形式的空白/空格? 這可能嗎? 這怎麼辦?如何驗證空白處/空白處? [Angular 2]

+0

你只需要修剪字段作爲雙向數據綁定。你也可以考慮自定義管道 – afmeva

+0

也許這篇文章可以幫助你http://blog.angular-university.io/introduction-to-angular-2-forms-template-driven-vs-model-driven/ – vinagreti

回答

6

也許這篇文章可以幫助你http://blog.angular-university.io/introduction-to-angular-2-forms-template-driven-vs-model-driven/

在這種方法中,你必須使用FormControl然後查看值的變化,然後你的面膜適用於價值。一個例子應該是:

... 
form: FormGroup; 
... 


ngOnInit(){ 
    this.form.valueChanges 
      .map((value) => { 
       // Here you can manipulate your value 
       value.firstName = value.firstName.trim(); 
       return value; 
      }) 
      .filter((value) => this.form.valid) 
      .subscribe((value) => { 
       console.log("Model Driven Form valid value: vm = ",JSON.stringify(value)); 
      }); 

} 
2

爲了避免表單子索引,只需在輸入字段中使用required attr。

<input type="text" required>

或者,提交後

當窗體submited,你可以使用str.trim()刪除空格形成開始和字符串的結尾。我做了一個提交功能,向您展示:

submitFunction(formData){ 

    if(!formData.foo){ 
     // launch an alert to say the user the field cannot be empty 
     return false; 
    } 
    else 
    { 
     formData.foo = formData.foo.trim(); // removes white 
     // do your logic here 
     return true; 
    } 

} 
+0

謝謝你你的幫助,但我需要的是避免用戶添加空格並保存表單。我相信有可能以某種方式驗證它。你怎麼看? – Eusthace

+0

我還沒有使用角度2形式的輸入掩碼。如果我這樣做,我會幫你的。但現在我不能。嘗試搜索角2的掩碼輸入;) – vinagreti

+0

謝謝!我會盡力找到它。 – Eusthace

22

您可以創建一個自定義驗證器來處理這個問題。

new FormControl(field.fieldValue || '', [Validators.required, this.noWhitespaceValidator]) 

添加noWhitespaceValidator方法您的組件

public noWhitespaceValidator(control: FormControl) { 
    let isWhitespace = (control.value || '').trim().length === 0; 
    let isValid = !isWhitespace; 
    return isValid ? null : { 'whitespace': true } 
} 

,並在HTML

<div *ngIf="yourForm.hasError('whitespace')">Please enter valid data</div> 
+3

我認爲我更喜歡這種方法,因爲它使規則可重用。即使是我的反應標記爲正確的。 – vinagreti

+2

要使其在其他組件中可重用:將'public'替換爲'export function',然後將其放入一個文件(例如:src/app/utils/no-whitespace.validator.rs),並添加該行以導入FormControl 。現在你可以將這個驗證器導入你喜歡的任何控件:) – rmcsharry

+0

@rmcsharry你是絕對正確的..這就是我們需要編寫和維護代碼的方式。 –

2

我所做的就是創建一個驗證器,除了我添加了該做的samething的角度進行的minLength修剪()

import { Injectable } from '@angular/core'; 
import { AbstractControl, ValidatorFn, Validators } from '@angular/forms'; 


@Injectable() 
export class ValidatorHelper { 
    ///This is the guts of Angulars minLength, added a trim for the validation 
    static minLength(minLength: number): ValidatorFn { 
     return (control: AbstractControl): { [key: string]: any } => { 
      if (ValidatorHelper.isPresent(Validators.required(control))) { 
       return null; 
      } 
      const v: string = control.value ? control.value : ''; 
      return v.trim().length < minLength ? 
       { 'minlength': { 'requiredLength': minLength, 'actualLength': v.trim().length } } : 
       null; 
     }; 
    } 

    static isPresent(obj: any): boolean { 
     return obj !== undefined && obj !== null; 
    } 
} 

然後我在我的app.component.ts推翻由角

import { Component, OnInit } from '@angular/core';  
import { ValidatorHelper } from 'app/common/components/validators/validator-helper'; 
import { Validators } from '@angular/forms'; 

@Component({ 
    selector: 'app-root', 
    templateUrl: './app.component.html' 
}) 
export class AppComponent implements OnInit { 
    constructor() { } 

    ngOnInit(): void {  
    Validators.minLength = ValidatorHelper.minLength; 
    } 
} 

提供的minLength功能現在到處角的的minLength內置驗證器會使用您的助手創建的minLength。

Validators.compose([ 
     Validators.minLength(2)   
    ]);