【问题标题】:How to validate age using Angularjs?如何使用 Angularjs 验证年龄?
【发布时间】:2013-08-26 13:07:14
【问题描述】:

我们正在为我们的项目使用 Angular js。以及我们通过 Angular js 处理的所有验证。

我们能够验证除下拉框之外的所有文本字段。

我们有三个用于日期字段的下拉框(dd mm yyyy)。现在我有两个问题...

  1. 我如何从这三个下拉列表中获取值以及如何形成日期。

  2. 然后,我想验证该日期(如果年龄大于 50 则设置错误标志)。我如何使用 Angular js 来做到这一点?如果用户选择年龄超过 50 岁,我想将表单设置为无效。

请给我这个建议?我对 Angular js 完全陌生。

【问题讨论】:

  • 显示你所拥有的一些代码

标签: validation angularjs angularjs-directive angularjs-scope


【解决方案1】:

我没有您提供的任何代码作为答案的依据,但这里有一个函数可以帮助您确定正确的年龄:

$scope.dateDiff = function(birthMonth, birthDay, birthYear) {
    var todayDate = new Date(),
        todayYear = todayDate.getFullYear(),
        todayMonth = todayDate.getMonth(),
        todayDay = todayDate.getDate(),
        age = todayYear - birthYear; 

    if (todayMonth < birthMonth - 1)
    {
      age--;
    }

    if (birthMonth - 1 === todayMonth && todayDay < birthDay)
    {
      age--;
    }
    return age;
};

$scope.dateDiff(8,15,1963); // return as 50 as birthday has passed
$scope.dateDiff(9,15,1963); // return as 49 as birthday has not yet happened

在您的 HTML 中,您可以使用 ng-options 允许用户从下拉列表中选择日期。

Day <select ng-model="selectedDay" ng-options="day as day.date for day in days"></select>

Here is a full working example.

由于您是 Angular 新手,请务必花时间了解这段代码的工作原理。 ng-options 起初可能看起来有点混乱,但当你开始了解 Angular 原理时,应该不会有问题。

【讨论】:

    猜你喜欢
    • 2014-04-04
    • 1970-01-01
    • 2014-03-29
    • 2013-04-10
    • 2014-08-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多