简体   繁体   English

我可以通过onBlur事件对文本框进行日期检查吗?

[英]Can I do a Date Check on a TextBox with a onBlur event?

I want to do a Date Check on a TextBox with a onBlur event. 我想使用onBlur事件在TextBox上执行日期检查。 I am not sure how to check the textbox in javascript on the aspx side. 我不确定如何在aspx端检查javascript中的文本框。 This is what I have so far 这就是我到目前为止

TodayDate= new Date();
function checkEnteredDate() {
if (document.getElementById('txtDate') > TodayDate) {
alert("You cannot select a date later than today.");
document.getElementById(TodayDate);
} 
}

This is already a javascript function, I just cannot get the value in the textbox for a comparison. 这已经是一个javascript函数,我只是无法在文本框中获取值进行比较。 Any suggestions? 有什么建议么?

You could try passing the "this" to the function: 您可以尝试将“ this”传递给函数:

<asp:TextBox ID="Text1" onblur="CheckEnteredDate(this);" runat="server" />

Edit : Here's how the javascript function would use that (roughly): 编辑 :这是javascript函数将使用它的方式(大致):

function CheckEnteredDate(passed) {
    if (new Date(passed.value) > new Date()) {
        alert('Date greater than today');
    }
}

Use the DateJs library to do date validation on the client-side like this... 像这样使用DateJs库在客户端进行日期验证...

function checkEnteredDate() {
  var elem = document.getElementById('txtDate');

  if(Date.parse(elem.value) > Date.today()) {
      alert("You cannot select a date later than today.");
      elem.select();
  }
}

If you're using Microsoft Ajax, Date parsing is already handled by the provided javascript reference libraries. 如果您使用的是Microsoft Ajax,则提供的javascript参考库已经处理了日期解析。

<asp:TextBox ID="Text1" onblur="CheckEnteredDate(this);" runat="server" />

Then on the function call: 然后在函数调用上:

function CheckEnteredDate(passed) {
    var value = Date.parseLocale(passed.value, 'd');
    if (isNaN(value))
        alert('Not a valid date.');
    if (value > new Date())
        alert('You cannot select a date later than today.');
}

您应该只能够对此添加一个函数调用到文本框的onBlur事件。

When you pass textbox to document.getElementById, it returns an HTML object not the text inside the textbox. 当您将文本框传递给document.getElementById时,它将返回HTML对象,而不是文本框内的文本。 Use value property to get the value entered by the user. 使用value属性获取用户输入的值。 See below: 见下文:

function checkEnteredDate() 
{
    var inputDate = document.getElementById('txtDate');
    if(inputDate == '')
    {
        alert('You must specify date.');
        return false;
    }

    inputDate = new Date(inputDate);
    var today = new Date();
    today.setHours(0, 0, 0, 0); //By default today's date will have time portion as well.

    if(inputDate > today)
    {
        alert('You can not select a date later than today');
        return false;
    }

    return true;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM