Angularjs驗(yàn)證用戶輸入的字符串是否為日期時(shí)間
在angularjs中,想在文本框中,驗(yàn)證用戶輸入的字符串是否為日期時(shí)間。
剛開始時(shí),Insus.NET想到的是正則,這只是驗(yàn)證到日期與時(shí)間的格式是否正確而已,而對(duì)于2月最后一天或是30或是31號(hào),還是無能為力。
因此,Insus.NET想使用angularjs的自定義指令來驗(yà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
};
}
}
}
接下來,你可以寫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ì)大家有所幫助,如果大家有任何疑問請(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實(shí)現(xiàn)的獲取焦點(diǎn)及失去焦點(diǎn)時(shí)的表單驗(yàn)證功能示例
Angular8 簡(jiǎn)單表單驗(yàn)證的實(shí)現(xiàn)示例

