Search code examples
angularjsvalidationangular-ui-datepicker

AngularJS date validation


How can I do date control validation in an AngularJS form for the following code ?

<label for="startDate" class="control-label">Start Date:</label>
<div class="">
    <input type="date" class="form-control" 
           id="startDate" ng-model="startDate" />
</div>

<label for="endDate" class="control-label">End Date:</label>
<div class="">
    <input type="date" class="form-control" 
           id="endDate" ng-model="endDate" />
</div>

<div class="alert alert-warning" ng-show="">
    // ??
</div>

If only one of the dates are entered, then the form should prompt to enter the other date. If both dates are empty, or both are entered, then it should successfully submit the form.


Solution

  • If you dont want to use any controller or js and want to do it with pure HTML. Try this Method

    Edit your HTML to :

    <label for="startDate" class="control-label">Start Date:</label>
    <div class="">
        <input type="date" class="form-control" 
               id="startDate" ng-model="startDate" />
    </div>
    
    <label for="endDate" class="control-label">End Date:</label>
    <div class="">
        <input type="date" class="form-control" 
               id="endDate" ng-model="endDate" />
    </div>
    
    <div class="alert alert-warning" ng-show="!startDate && endDate ||startDate && !endDate ">
        // Do what ever you want to do here 
    </div>
    

    Added this answer too so that you can choose which ever best suits you. If you want to do more functionality on the submit I highly suggest you using the Controller. If you are just interested in the UI go ahead with the simple HTML solution