5

I've written a custom form control which is in fact a wrapper around p-calendar component. Component definition looks like below (Note:- I've removed some code to make it simple)

export class MyDatePickerComponent implements ControlValueAccessor, OnInit, OnChanges {
  @Input() _myDate : Date;
  @Input() control: FormControl;  
  @Input() dateFormat: string;  
  @Output() myDateChange : EventEmitter<Date> = new EventEmitter<Date>();

  propagateChange: any = () => {};
  validateFn:any;

  get myDate(){ 
    return this._myDate;
  }
  set myDate(val){    
    this._myDate = val;        
    this.propagateChange(this._myDate);
  }
  constructor() { }

  //OnInit Implementation
  ngOnInit() {
    this.validateFn = (c: FormControl) => {
      if (c.value == null) {
        return null;
      }
      let dateErr = { invalidDate: { valid: false } };      
      let userDate = moment(c.value, dateFormat, true);
      return userDate.isValid() ? null : dateErr;
    };
  }

  //ControlValueAccessor Implementation
  writeValue(obj:any):void {    
    this.myDate = obj;
  }

  registerOnChange(fn:any):void {
    this.propagateChange = fn;    
  }

  registerOnTouched(fn:any):void { }

  validate(c: FormControl) {
    return this.validateFn(c);
  }
}

Template for the custom component is:

<div class="form-group">
  <div class="col-md-2  col-sm-12  col-xs-12">
    <label class="control-label">Some date caption</label>
  </div>
  <div class="col-md-10  col-sm-12  col-xs-12">
    <p-calendar [(ngModel)]="tbDate" [dateFormat]="dateFormat" [showIcon]="true" readonlyInput="false"
      (ngModelChange)="tbDateChange.emit($event)">
    </p-calendar>    
  </div>  
</div>

Now when user manually enters a wrong date value into the date text box, the validator is invoked but the c.value property inside validateFn contains null.

The end result is if the textbox is empty or contains invalid date my validator doesn't work as the value is always null.

Is there any way to get the value manually entered by the user to perform validation and display validation errors.

Note:- I am using PrimeNG 1.0.0-RC3

Antikhippe
  • 6,316
  • 2
  • 28
  • 43
A J Qarshi
  • 2,772
  • 6
  • 37
  • 53
  • why not use readonlyInput and force the user to select a proper date from the calendar? – John Baird Nov 11 '16 at 17:18
  • in fact `readonlyInput` is dynamically set in my actual component. I hard-coded its value to `false` in the sample code above. So the component must also handle manual input. – A J Qarshi Nov 12 '16 at 09:19

0 Answers0