简体   繁体   English

当用户单击按钮时输入无效的日期格式时,如何显示验证错误?

[英]how to show validation error when user enter invalid date format on button click?

is there any way to show validation error message or border become red when user enter invalid date format?.In my demo app there two input field in which I am showing date like this "16-jun-1989" .Now user edit this field only in this format (that is valide) if user enter invalid format I want to show error message on button click or border become red on button click here is my code http://plnkr.co/edit/xoTH3uJZSVx0W78rwhMt?p=preview 用户输入无效的日期格式时,是否有任何方法可以显示验证错误消息或边框变为红色?。在我的演示应用程序中,有两个输入字段,其中我正在显示日期,例如“ 1989年6月16日”。仅当用户输入无效格式时才采用这种格式(即有效), 我要在单击按钮时显示错误消息,或者单击按钮时边框变为红色,这是我的代码http://plnkr.co/edit/xoTH3uJZSVx0W78rwhMt?p=preview

var app = angular.module('plunker', ['angularMoment']);

app.controller('MainCtrl', function($scope ,moment) {
  $scope.name = 'World';
  console.log(moment)
  var d = new Date(613938600000);
  $scope.c = {
   ab: {
      name:'abc'
    },
   date: {
      name: moment(d).format('DD-MMM-YYYY')
    }
    };

    $scope.onclick =function(){
        console.log($scope.c)
    }

});

Since you are using moment already, check if the date is valid with: 由于您已经在使用时刻,请通过以下方法检查日期是否有效:

moment($scope.c.date.name).isValid()

A working example here. 这里的工作示例

Though this already has answer. 虽然这已经有答案。 You might also be interested in ensuring the date is specified exactly how you want it. 您可能还对确保准确指定日期的方式感兴趣。 The validation in the accepted answer is not strict: This should fix that: 接受的答案中的验证不严格:这应解决以下问题:

$scope.onclick = function() {
    if (!moment($scope.c.date.name, 'DD-MMM-YYYY').isValid()) {
      alert('Date must be in the format 02-Nov-2018');
    } else {
      alert('All good');
    }
}

The second argument to the moment function ensures this strictness. moment函数的第二个参数确保了这种严格性。

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

相关问题 当用户单击Enter按钮时触发按钮 - Trigger a button when the user click in Enter button 用户单击使用Jquery的Enter键时如何触发按钮? - How to trigger the button when user click enter key using Jquery? 当用户使用jquery输入无效的日期或月份时,下一步按钮将被禁用 - Next button will be disabled when user enter invalid date or month using jquery 当用户输入多个“一个”或 1 个字符时如何显示错误? - How to show error when user enter more than `one` or 1 character? 简单的javascript验证,在输入无效日期格式时阻止用户提交表单? - Simple javascript validation that stops user from submitting form when entering invalid date format? 用户选择错误的日期时如何显示验证消息? - how to show validation message when user choose wrong date? 如何在一次单击时隐藏按钮,它将显示当前时间和日期 - How to hide the button when click at a time it will show the current time and date 当用户单击GridView中的“编辑”按钮时如何显示下载图像 - How to show download image when user click on edit button in GridView 如何在单击按钮时显示验证消息? - how to show validation message on button click? 如果用户没有输入正确的格式,如何返回“无效的电子邮件” - How to Return 'Invalid Email' if User Doesn't Enter Correct Format
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM