Angularjs驗(yàn)證用戶輸入的字符串是否為日期時(shí)間
在angularjs中,想在文本框中,驗(yàn)證用戶輸入的字符串是否為日期時(shí)間。
剛開(kāi)始時(shí),Insus.NET想到的是正則,這只是驗(yàn)證到日期與時(shí)間的格式是否正確而已,而對(duì)于2月最后一天或是30或是31號(hào),還是無(wú)能為力。
因此,Insus.NET想使用angularjs的自定義指令來(lái)驗(yàn)證解決此問(wèn)題。
在ASP.NET MVC的項(xiàng)目中,創(chuàng)建一個(gè)控制器,并創(chuàng)建一個(gè)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 }; } } }
接下來(lái),你可以寫(xiě)Directive了,那是一個(gè)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應(yīng)用此angularjs的屬性:
演示:
以上所述是小編給大家介紹的Angularjs驗(yàn)證用戶輸入的字符串是否為日期時(shí)間,希望對(duì)大家有所幫助,如果大家有任何疑問(wèn)請(qǐng)給我留言,小編會(huì)及時(shí)回復(fù)大家的。在此也非常感謝大家對(duì)腳本之家網(wǎng)站的支持!
相關(guān)文章
AngularJS 模塊詳解及簡(jiǎn)單實(shí)例
本文主要介紹AngularJS 模塊,這里幫大家整理了相關(guān)資料,詳細(xì)介紹了AngularJS的基礎(chǔ)知識(shí),有需要的朋友可以參考下2016-07-07使用AngularJS中的SCE來(lái)防止XSS攻擊的方法
這篇文章主要介紹了使用AngularJS中的SCE來(lái)防止XSS攻擊的方法,依靠合理地轉(zhuǎn)碼為HTML來(lái)預(yù)防跨站腳本漏洞共計(jì),需要的朋友可以參考下2015-06-06簡(jiǎn)單說(shuō)說(shuō)angular.json文件的使用
這篇文章主要介紹了簡(jiǎn)單說(shuō)說(shuō)angular.json文件的使用,小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2018-10-10

AngularJS實(shí)現(xiàn)的獲取焦點(diǎn)及失去焦點(diǎn)時(shí)的表單驗(yàn)證功能示例

Angular8 簡(jiǎn)單表單驗(yàn)證的實(shí)現(xiàn)示例