源码网商城,靠谱的源码在线交易网站 我的订单 购物车 帮助

源码网商城

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

  • 时间:2021-10-07 00:11 编辑: 来源: 阅读:
  • 扫一扫,手机访问
摘要:Angularjs验证用户输入的字符串是否为日期时间
在angularjs中,想在文本框中,验证用户输入的字符串是否为日期时间。 刚开始时,Insus.NET想到的是正则,这只是验证到日期与时间的格式是否正确而已,而对于2月最后一天或是30或是31号,还是无能为力。 因此,Insus.NET想使用angularjs的自定义指令来验证解决此问题。 在ASP.NET MVC的项目中,创建一个控制器,并创建一个Action: [img]http://files.jb51.net/file_images/article/201706/201706011412091.jpg[/img] 控制器源代码:
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文件: [img]http://files.jb51.net/file_images/article/201706/201706011412104.jpg[/img] 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的属性: [img]http://files.jb51.net/file_images/article/201706/201706011412105.jpg[/img]  演示: [img]http://files.jb51.net/file_images/article/201706/201706011412106.gif[/img] 以上所述是小编给大家介绍的Angularjs验证用户输入的字符串是否为日期时间,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对编程素材网网站的支持!
  • 全部评论(0)
联系客服
客服电话:
400-000-3129
微信版

扫一扫进微信版
返回顶部