2017-10-05 71 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; 
}