angular2 forms - Image validation. Minimum width. Angular 2 -
i'm trying write custom directive input image validation. validate image chosen have 'width' higher x value (300 in example).
<input id="imagefile" minwidth="300" minheight="300" name="image" type="file" ngmodel #image="ngmodel"> <div *ngif="image.invalid"> <p *ngif="image.errors.width" >width should higher 300px!</p> </div>
import { directive, hostlistener, input } '@angular/core'; import { abstractcontrol, ng_validators, validator, validatorfn } '@angular/forms'; @directive({ selector: '[minwidth]', providers: [{provide: ng_validators, useexisting: imageminwidthdirective, multi: true}] }) export class imageminwidthdirective implements validator { @input() minwidth: number; private width = 0; file: any; image: any; @hostlistener('change', ['$event']) onchange($event) { const files = $event.target.files || $event.srcelement.files; this.file = files[0]; } validate(control: abstractcontrol): {[key: string]: any} { return this.minwidth ? this.minwidthvalidator()(control) : null; } minwidthvalidator(): validatorfn { return (control: abstractcontrol): {[key: string]: any} => { this.image = new image(); this.image.onload = event => { this.width = event.path[0].width; alert(this.image.width); }; this.image.src = window.url.createobjecturl(this.file); return this.width < this.minwidth ? {'width': {value: 'hello'}} : null; }; } }
Comments
Post a Comment