Search code examples
javascriptangularjsdatepickerangular-ui-bootstrapangular-ui

Angular ui: bootstrap datepicket input validation


I'm using this datepicker. As of now, the user can write anything he likes in the input field which is not what I want.

My code:

session.js

  session.getDateFormat = function() {
            return 'yyyy-MM-dd';
        };

        session.formatDate = function(date) {
            return $filter('date')(date, session.getDateFormat());
        };

Controller.js

vm.dateFormat = session.getDateFormat();
function submit() {
date : session.formatDate(vm.data.date)
 }

The code is much longer but that basically the part concerning the date. And HTML

<input type="text" class="form-control" uib-datepicker-popup="{{vm.dateFormat}}" placeholder="{{vm.dateFormat}}" ng-model="vm.data.date" is-open="vm.dateOpened" ng-required="true" ng-disabled="disabled" />

The admin can choose if he wants getDateFormat to accept yyyy-mm-dd or dd-mm-yyyy etc.

What I want:

  1. To verify that the user has input the date is the right format, otherwise to clear the field automatically and display an error message along with the right date format as a hint to the user. All that must be done before pressing submit.
  2. Not allowing the user to enter letters obviously
  3. No hard coded html regex, I want something to check if the input is the same as getDateFormat, otherwise clear the field and display an error.
  4. No Jquery, I don't use Jquery in the entire project.
  5. If you have any other datepicker in mind that works with angular and bootstrap without using Jquery, let me know.

Solution

  • I had to update to angular-ui 1.3.3 and then I had to give the date input a name 'datepicker' and the form a name 'frm' and then

    <div ng-if="!frm.datepicker.$error.required"">
    <div class="datepicker-error" ng-if="frm.datepicker.$invalid">
    some error message
    </div></div>
    

    I didn't clear the field since if the user didn't finish typing it's going to be invalid and hence might be cleared. If anyone has a better solution let me know.