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

发布时间:2020-08-30 02:10:08 作者:Insus.NET
来源:脚本之家 阅读:262

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

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

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

在ASP.NET MVC的项目中,创建一个控制器,并创建一个Action:

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

控制器源代码:

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文件:

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

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验证用户输入的字符串是否为日期时间

 演示:

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

以上所述是小编给大家介绍的Angularjs验证用户输入的字符串是否为日期时间,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对亿速云网站的支持!

推荐阅读:
  1. 验证域名是否为该用户的域名
  2. php验证用户名密码是否为空的方法

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

angularjs 验证 字符串

上一篇:javascript ES6 新增了let命令使用介绍

下一篇:vue获取form表单的值示例

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》