溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

Angularjs驗(yàn)證用戶輸入的字符串是否為日期時(shí)間

發(fā)布時(shí)間:2020-08-30 02:10:08 來(lái)源:腳本之家 閱讀:278 作者:Insus.NET 欄目:web開發(fā)

在angularjs中,想在文本框中,驗(yàn)證用戶輸入的字符串是否為日期時(shí)間。

剛開始時(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:

Angularjs驗(yàn)證用戶輸入的字符串是否為日期時(shí)間

控制器源代碼:

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),你可以寫Directive了,那是一個(gè)js文件:

Angularjs驗(yàn)證用戶輸入的字符串是否為日期時(shí)間

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í)間

 演示:

Angularjs驗(yàn)證用戶輸入的字符串是否為日期時(shí)間

以上所述是小編給大家介紹的Angularjs驗(yàn)證用戶輸入的字符串是否為日期時(shí)間,希望對(duì)大家有所幫助,如果大家有任何疑問(wèn)請(qǐng)給我留言,小編會(huì)及時(shí)回復(fù)大家的。在此也非常感謝大家對(duì)億速云網(wǎng)站的支持!

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI