Angularjs validation - bootstrap datepicker input is not recognized

2.9k views Asked by At

If you read following Angularjs validations, you understand that: Message will appear if user interacted and did not fill the date manually. The problem is when date is filled using the datepicker the input is not recognized by Angularjs and still consider $invalid true, so the message remains there which is confusing/problem although date is already filled using datepicker!

<div class="form-group" ng-class="{ 'has-error' : AddForm.Birthdate.$invalid && !AddForm.Birthdate.$pristine }"> 
     <input type="text"  required data-provide="datepicker"  class="form-control" name="Birthdate" ng-model="Birthdate"  />
     <span ng-show="AddForm.Birthdate.$invalid  && !AddForm.Birthdate.$pristine" class="help-block" >
  Birthdate is required.
     </span>
</div>
4

There are 4 answers

2
guilhebl On BEST ANSWER

You can either validate it prior to form submit, or else hook a listener on your datepicker to manually set the model property Birthdate value.

It seems bootstrap datepicker is built on top of JQuery datepicker, manually setting the value would be a bad practice you can refer to: Update Angular model after setting input value with jQuery

a better approach would be to use some built-in angular component such as the ones from:

https://angular-ui.github.io/bootstrap/ http://dalelotts.github.io/angular-bootstrap-datetimepicker/ https://github.com/dalelotts/angular-bootstrap-datetimepicker

0
shubhamkes On

Was facing the issue, and its because of the picker you are using is built on top of Jquery which remains undetectable by the scope on update.

For my new project I have added another library and its pretty awesome. See the documentation http://dalelotts.github.io/angular-bootstrap-datetimepicker

Providing the piece of code for which I have added a wrapper directive

0
shubhamkes On

I discovered a new way for this problem-

First of all create an id for that input box and then create a function say $scope.assign(), which simply assign the id value to the model of that input. Something Like this-

$scope.assign = function() {
$scope.modelValue = $('#idName').val();
}

Now use ng-bind="assign()" to your input box.

It worked for me :)

0
shubhamkes On

My Previous Answer was based on work around and because at that time of answer I was pretty new to the angular and now instead of that I will recommend, not to use an library which is built on top of Jquery in Angular project. Instead prefer angular libraries.

Coming on the topic- For date time picker I found one very good library

https://github.com/indrimuska/angular-moment-picker

You can find more libraries in built in angular, but I found it pretty useful for other validations too like min-date, max-date validation.

Using this library will solve the issue of validation for sure and its pure Angular way.