当前位置: 移动技术网 > IT编程>脚本编程>AngularJs > Angularjs验证用户输入的字符串是否为日期时间

Angularjs验证用户输入的字符串是否为日期时间

2018年04月26日  | 移动技术网IT编程  | 我要评论

在angularjs中,想在文本框中,验证用户输入的字符串是否为日期时间。

刚开始时,insus.net想到的是正则,这只是验证到日期与时间的格式是否正确而已,而对于2月最后一天或是30或是31号,还是无能为力。

因此,insus.net想使用angularjs的自定义指令来验证解决此问题。

在asp.net mvc的项目中,创建一个控制器,并创建一个action:

控制器源代码:

using system;
using system.collections.generic;
using system.globalization;
using system.linq;
using system.web;
using system.web.mvc;
namespace insus.net.controllers
{
 public class commonscontroller : controller
 {
 public jsonresult validatedate(string date)
 {
  object _data;
  datetime dt;
  if (datetime.tryparse(date, out dt))
  {
  _data = new { result = true };
  }
  else
  {
  _data = new { result = false };
  }
  return new jsonresult
  {
  data = _data,
  contentencoding = system.text.encoding.utf8,
  jsonrequestbehavior = jsonrequestbehavior.allowget
  };
 }
 }
}

接下来,你可以写directive了,那是一个js文件:

validatedate的angularjs代码:

airexpressapp.directive('validatedate', function ($http, $q) {
 return {
 restrict: 'ae',
 require: 'ngmodel',
 link: function ($scope, element, attributes, ngmodelcontroller) {
  ngmodelcontroller.$asyncvalidators.datavalid = function (modelvalue, viewvalue) {
  var deferred = $q.defer();
  var obj = {};
  obj.date = modelvalue;
  $http({
   method: 'post',
   url: '/commons/validatedate',
   datatype: 'json',
   headers: {
   'content-type': 'application/json; charset=utf-8'
   },
   data: json.stringify(obj),
  }).then(function (response) {
   if (ngmodelcontroller.$isempty(modelvalue) || response.data.result) {
   deferred.resolve();
   } else {
   deferred.reject();
   }
  });
  return deferred.promise;
  };
 }
 }
});

html的input应用此angularjs的属性:

 演示:

以上所述是小编给大家介绍的angularjs验证用户输入的字符串是否为日期时间,希望对大家有所帮助

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网