looking through angular2 api control class see
minlength(minlength: number) : function
i understand function does.
i wondering though if description of went wrong when validation fails not placed right there in function.
for instance, wondering if function not be
minlength(minlength: number, description: string) : function
where description describes reason error shown below
control firstctrl = new control( '', validators.minlength(2, description: 'minium of 2 characters required) );
i have not been able find similar validators in api. if 1 exist happy if link/explanation shared.
looking forward seeing feedback.
there no builtin validators take parameter error description. can write own.
let's take example builtin minlength
validator. add second parameter called desc that'll hold custom error message.
class customvalidators { static minlengthwithdescription(minlength: number, desc: string): function { return (control: modelmodule.control): {[key: string]: any} => { return v.length < minlength ? {"minlength": { "requiredlength": minlength, "actuallength": v.length, "desc": desc // here pass our custom error message } } : null; }; } }
as see barely touched original one. it's simple checking in our view if error message exists
<form [ngformmodel]="myform"> <p> year: <input ngcontrol="year"> // use elvis operator check if error exists or not // if exists print error message {{myform.controls.year.geterror('minlength')?.desc}} </p> </form>
and set error message want show
export class app { year: control = new control('', customvalidators.minlengthwithdescription(4, 'wrong ammount of numbers')); }
here's plnkr example working.
Comments
Post a Comment