currently i am learning angular2 with validation part,I am not able to validate simple customer text box field
Here is my HTML Code
<div class="col-xs-12 col-sm-12 col-md-6 col-lg-6 padding-lft-rght-0">
<div class="form-control setup-form margin-btm">
<label test_id="lblcustname" class="control-label col-xs-12 col-sm-4 col-md-4 col-lg-3" for="">
{{ 'CUSTOMER.CNAME' | translate }} <span class="mandatory">*</span>
</label>
<div class="col-xs-12 col-sm-8 col-md-8 col-lg-8 padding-left-0">
<input type="text" id="txtName" class="form-control" required maxlength="100" name="CustomerName" [(ngModel)]="customerObj.CustomerName" (ngModelChange)="checkCustomeName($event)" />
</div>
</div>
</div>
and below my Typescript code
checkCustomeName(event) {
if (event === "") {
this.isCustomerNameEmpty = false;
}
else {
var textbox= document.getElementById('txtName');
if (textbox.nodeValue.length > 100)
{
this.isCustomerNameexceed = false;
}
this.isCustomerNameexceed = true;
}
}
So whenever i am debugging using chrome i am not able to get any value in below line..
var textbox= document.getElementById('txtName');
So is this the correct way to do validation in typescript.
I think you're only getting the element with
var textbox = document.getElementById('txtName');
Try
var textbox = document.getElementById('txtName').value;
Better yet, since you're using databinding, you should be able to use
var textbox = customerObj.CustomerName;
if (textbox.length > 100) ...
If you want to do the Angular approach, check out form validation in the angular docs
First that you have to consider. This template:
<input [(ngModel)]="some"/>
is same as:
<input [ngModel]="some" (ngModelChange)="some = $event">
Having
<input [(ngModel)]="some" (ngModelChange)="someHandler($event)">
is bad idea.
Basically, there is "Angular2 way" for doing validation https://angular.io/docs/ts/latest/cookbook/form-validation.html , but whatever.
Another thing: you do not need reference to txtField to get value.
checkCustomeName(event) - where event is your value.ngOnChanges() lifecycle hook https://angular.io/docs/ts/latest/guide/lifecycle-hooks.html