2017-10-05 70 views
2

我是Angular的新手。我正在使用角4反應形式,並找出如何執行自定義驗證。以下是我的數字執行Angular中的日期和貨幣驗證(4)

function numberValidator(c: AbstractControl): { [key: string]: boolean } | null { 
    if (c.pristine) { 
     return null; 
    } 
    if (c.value.match(/.*[^0-9].*/)) { 
     return { 'numeric': true }; 
    } 
    return null; 
} 

phoneControl: ['', [Validators.required, Validators.minLength(10), Validators.maxLength(10), numberValidator]], 

我想了解如何執行貨幣(有或沒有兩位小數)和最重要的日期字段。

原諒我,如果這是在別處回答,但我無法找到任何樣品的角度(4)

感謝您的時間

+0

你爲什麼不使用CurrencyPipe? https://angular.io/api/common/CurrencyPipe – Wandrille

+0

感謝您的建議。糾正我,如果我錯了。貨幣管道是用於將顯示值轉換爲正確的?我正在尋找文本框條目的驗證。 – Vinod

+0

myBad!你是對的! – Wandrille

回答

4

你需要什麼樣的日期驗證嗎?只是價值是有效的日期?如果您在輸入元素上設置了type="date",瀏覽器將確保只輸入有效的日期。

與您顯示的號碼驗證器和任何貨幣驗證器相同。您應該能夠在輸入元素上設置type="number",並且不需要驗證器。

如果你仍然想要執行自己的驗證,你可以使用正則表達式,就像你的例子。

只需查看貨幣和日期的正則表達式即可。對於日期,像這樣:Javascript - Regex to validate date format

+0

感謝您的回覆。設置類型=「日期」是否適用於所有瀏覽器或僅支持HTML 5的瀏覽器。爲了更安全一方,我想在組件方面做我自己的驗證。所以你推薦正則表達式進行自定義驗證?謝謝 – Vinod

+0

這就是你在你的例子中做的:'(c.value.match(/.*[^ 0-9]。* /))'所以我假設你想要類似的東西?您可以使用以下方式確定哪些瀏覽器支持特定功能:https://caniuse.com/#search=type%3D%22date%22 – DeborahK

+0

感謝您的回覆。 – Vinod

1

創建一個自定義驗證處理格式MM/DD/YYYY和MMDDYYYY

function dateValidator(c: AbstractControl): { [key: string]: boolean } | null { 
    if (c.pristine) { 
     return null; 
    } 
    if ((c.value !== undefined && c.value !== '' && c.value != null)) { 

     var month = null; 
     var day = null; 
     var year = null; 
     var currentTaxYear = Number(new Date().getFullYear() - 1); 
     if (c.value.indexOf('/') > -1) { 
      var res = c.value.split("/");   
      if (res.length > 1) { 
       month = res[0]; 
       day = res[1] 
       year = res[2]; 
      }        
     } 
     else { 
      if (c.value.length == 8) { 
       month = c.value.substring(0, 2); 
       day = c.value.substring(2, 4); 
       year = c.value.substring(4, 8); 
      }    
     } 
     if (isNaN(month) || isNaN(day) || isNaN(year)) { 
      return { 'dateInvalid': true }; 
     } 
     month = Number(month); 
     day = Number(day); 
     year = Number(year); 
     if (month < 1 || month > 12) { // check month range 
      return { 'dateInvalid': true }; 
     } 
     if (day < 1 || day > 31) { 
      return { 'dateInvalid': true }; 
     } 
     if ((month === 4 || month === 6 || month === 9 || month === 11) && day === 31) { 
      return { 'dateInvalid': true }; 
     } 
     if (month == 2) { // check for february 29th 
      var isleap = (year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0)); 
      if (day > 29 || (day === 29 && !isleap)) { 
       return { 'dateInvalid': true }; 
      } 
     } 
     if (year !== currentTaxYear) { 
      return { 'dateYearGreaterThanTaxYear': true }; 
     } 
    } 
    return null; 
}