简体   繁体   English

为什么我在Angular2中进行自定义验证不起作用

[英]Why is my custom validation in Angular2 not working

Here are two angular2 custom validations that I wrote, the first one validateAge works, but the second one validateDob does not ... the difference is the validateAge uses the component that I am on and is a text based field, the second one needs to use a Date Entry field and find the difference between today's date and the birthdate to find the actual age and then measure it against the age field. 这是我编写的两个angular2自定义验证,第一个validateAge有效,但是第二个validateDob不起作用...不同之处在于validateAge使用我所在的组件并且是基于文本的字段,第二个需要使用日期输入字段,找到今天的日期和生日之间的差,以找到实际年龄,然后根据年龄字段进行测量。 but something is not right ... any ideas 但是有些事情不对...任何想法

function validateAge(control: FormControl): { [s: string]: boolean } {
  if (parseInt(control.value) <= 0) {
    return {invalidAge: true};
  }
}

function validateDob(control: FormControl): {[s:string]: boolean}{
  var today = new Date();
  var calcAge = today - control.value;
  if (calcAge != parseInt([{age}]) ){
    return {invalidDate: true}
  }
}

The issue you have here is that your control.value is not a Date object, but rather the string representation. 这里的问题是您的control.value不是Date对象,而是字符串表示形式。

var today = new Date();

Difference in milliseconds between the current timestamp and the entered value 当前时间戳和输入值之间的毫秒差

var diff = today - new Date(control.value);

divide by ms per year and take the floor 每年除以ms并发言

var calcAge = Math.floor(diff/ (1000*60*60*24*365)));

Now do whatever comparison you need against the appropriate value. 现在,将所需的任何值与适当的值进行比较。 You didn't show us what your age object is so I don't actually know what comparison you're looking for. 您没有向我们显示您的年龄对象是什么,因此我实际上不知道您要寻找的比较对象。

if (calcAge < someAgeThreshold) ){
    return {invalidDate: true}
} else {
    return null;
}

Also note that with custom validation the validator returns no error when you return null and anything with a value is considered to have an error. 还要注意,使用自定义验证时,当您返回null时,验证器不会返回任何错误,并且带有值的任何内容都将被视为错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM