Search code examples
htmlangularjsinternet-explorerhtml-input

How can I disable a Submit button, until after legitimate date is entered in an input date field?


I have a form that is used as a filter. This is the code for the date input field.

<label>Date:</label>
<input type="text" id="dateFilter"
       ng-model="gridFilters.dateFilter"
       placeholder="MM/DD/YYYY"
       ng-disabled="loadingData" />
<span class="glyphicon glyphicon-calendar" style="width: 30px"></span>

When the angular controller initializes, the gridFilters.dateFilter value is set to undefined and should not default to anything. This is the correct behavior.

This is the code for my submit button. I'd like for the button to remain disabled until a user selects/enters a valid date.

<button type="button"
        class="btn btn-success pull-right"
        style="top: -5px; margin-left: 20px"
        ng-click="filter()"
        ng-enabled="gridFilters.dateFilter!== null && gridFilters.dateFilter!== undefined && Date.parse(gridFilters.dateFilter)"
        ng-hide="session.Status !== 0">
    Search
</button>

As you can see, I've made multiple attempts at checking the value of the gridFilters.dateFilter value. None of this works. Specifically, when I load the page, my button is enabled as if everything is if a proper date has been entered into the selector. How can I test if the date value is, in fact, a date? Also, this must work in Internet Explorer. I doubt this will make a difference, but IE is our corporate, preferred browser.


Solution

  • You need to use ng-disabled - there is no HTML attribute called enabled.

    And try this:

    <button type="button"
            class="btn btn-success pull-right"
            style="top: -5px; margin-left: 20px"
            ng-click="filter()"
            ng-disabled="gridFilters.dateFilter === null || gridFilters.dateFilter === undefined || Date.parse(gridFilters.dateFilter)"
            ng-hide="session.Status !== 0">
        Search
    </button>
    

    This ng-disabled="gridFilters.dateFilter === null || gridFilters.dateFilter === undefined" is working 100%

    But for the Date.parse(gridFilters.dateFilter) I'm not sure if it will work or not.

    Another approach is :

    <form name="dataForm" novalidate ng-submit="submitForm()">
       <input type="date" name="date" class="form-control" required 
              ng-model="gridFilters.dateFilter">
       <button type="submit"
               class="btn btn-success pull-right"
               style="top: -5px; margin-left: 20px"
               ng-click="filter()"
               ng-disabled="dataForm.$invalid"
               ng-hide="session.Status !== 0">
          Search
       </button>
    </form>