valor-software / ngx-bootstrap

Fast and reliable Bootstrap widgets in Angular (supports Ivy engine)
https://valor-software.com/ngx-bootstrap
MIT License
5.53k stars 1.69k forks source link

Datepicker accept random string after select a valid date #5935

Open HatemAlhasani opened 4 years ago

HatemAlhasani commented 4 years ago

Datepicker accept random string after select a valid date. sometimes the first attempt datepicker is working but in general the user able to type a random string after selecting a valid date

Versions of ngx-bootstrap, Angular, and Bootstrap:

ngx-bootstrap: 6.1.0

Angular: 10

Bootstrap: 3

Build system: Angular CLI

Expected behavior Datepicker strictly accept only valid date with same format and rid of all extra symbols and letters for example the inputFormat is "DD/MM/YYYY" and user select or type a valid date like "22/09/2020abcd" should be have the value "22/09/2020" or format is "YYYY" then expected value only year not "2020abc" or "2020 abc".

image

p91paul commented 1 year ago

I wanted to open a pull request, but you guys have a nice contributing policy and I lack the time to contribute properly for now.

Please look at https://github.com/p91paul/ngx-bootstrap/commit/475468edc18ad6c618b2d7f483bba463c5e4369b, that code enables strict parsing and fixes the issue. Could you please include it with unit tests and all that is required?

Just a note: reading 22/09/2020abcd as 22/09/2020 might be fine, but reading 01/01/2abc023 as 01/01/0002 is not.

p91paul commented 1 year ago

For anyone struggling with this, as a ugly hack, I did the following in my component:

Template

<input type="text" class="form-control" placeholder="Datepicker" bsDatepicker [(ngModel)]="datepickerModel" #input=ngModel />

Component

...
@ViewChild('input') input: NgModel;
...
  ngAfterViewInit(): void {
    const bsDatepickerInputDirective: BsDatepickerInputDirective = this.input.valueAccessor as BsDatepickerInputDirective;
    bsDatepickerInputDirective.writeValue = value => {
      const self = (bsDatepickerInputDirective as any);
      if (!value) {
        self._value = void 0;
      } else {
        const _localeKey = self._localeService.currentLocale;
        const _locale = getLocale(_localeKey);
        if (!_locale) {
          throw new Error(
            `Locale "${_localeKey}" is not defined, please add it with "defineLocale(...)"`
          );
        }

        self._value = parseDate(value, self._picker._config.dateInputFormat, self._localeService.currentLocale, true);

        if (self._picker._config.useUtc) {
          self._value = utcAsLocal(self._value);
        }
      }
      self._picker.bsValue = self._value;
    };
  }
ntt77 commented 10 months ago

@p91paul It's not work