简体   繁体   中英

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. I am not sure how to check the textbox in javascript on the aspx side. 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. Any suggestions?

You could try passing the "this" to the function:

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

Edit : Here's how the javascript function would use that (roughly):

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...

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.

<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. Use value property to get the value entered by the user. 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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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