mpsbhat
mpsbhat

Reputation: 2773

validate date format using jqueryUI parseDate method

I have a sample fiddle where i'm trying to validate date format as

 $('button').click(function() {
    $('#error').text('');
    var dateParse = $.datepicker.parseDate("dd/mm/yy", $("#datepicker").val());
    if (dateParse) {
      $('#error').text(dateParse);
    } else {
      $('#error').text('invalid date format');
    }
  });

But the error is not showing. What is wrong in the code?

Upvotes: 2

Views: 6649

Answers (1)

Gvidas
Gvidas

Reputation: 1964

Error not showing, because error occurs in parseDate() function, because of invalid date. You need to handle that error first. Here's jsFiddle

$(function() {
  $("#datepicker").datepicker({
    dateFormat: 'dd/mm/yy',
  });

  $('button').click(function() {
    $('#error').text('');
    try {
    var dateParse = $.datepicker.parseDate("dd/mm/yy", $("#datepicker").val());
    } catch (e) {}
    if (dateParse) {
      $('#error').text(dateParse);
    } else {
      $('#error').text('invalid date format');
    }
  });
});
<link href="https://code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<p>Date:
  <input type="text" id="datepicker">
</p>
<p id="error">

</p>
<button>
  Validate
</button>

And i suggest to show that error instead of your custom:

$(function() {
  $("#datepicker").datepicker({
    dateFormat: 'dd/mm/yy',
  });

  $('button').click(function() {
    $('#error').text('');
    try {
    var dateParse = $.datepicker.parseDate("dd/mm/yy", $("#datepicker").val());
    if (dateParse) {
      $('#error').text(dateParse);
    }
    } catch (e) {$('#error').text(e);}
  });
});
<link href="https://code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<p>Date:
  <input type="text" id="datepicker">
</p>
<p id="error">

</p>
<button>
  Validate
</button>

Upvotes: 3

Related Questions