在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驗證用戶輸入的字符串是否為日期時間,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對武林網網站的支持!
新聞熱點
疑難解答