Rachmat Chang
Rachmat Chang

Reputation: 197

Make validator for space in Angular2

I just to ask something about validation use pattern in angular 2.

enter image description here

This picture shows my page. In the red box, I want to set validation. My validation is this textbox can't input space and make trim. just simple but I can't do this.

ngOnInit() {
    this.submitButtonText = 'Save';
    this.form = this.fb.group({
        'id': [],
        'parent': ['-1', Validators.compose([Validators.required])],
        'name': ['', Validators.compose([Validators.required])],
        'title': ['', Validators.compose([Validators.required])],
        'router': ['/apps'],
        'description': ['', Validators.compose([Validators.required])]
    });
    this.parent = this.form.controls['parent'];
    this.name = this.form.controls['name'];
    this.title = this.form.controls['title'];
    this.router = this.form.controls['router'];
    this.description = this.form.controls['description'];
    this.toggleFormControl("router",false);

    this.service.getParent()
        .subscribe(
            data => this.setParent(data['menu']),
            err => this.logError(err),
            () => this.finishedGetIndexList('Save')
        );
    this.statusForm = 'Add';
    if (this.id) {
        this.fetchData();
    }
}

the HTML is

<div class="form-group row" [ngClass]="{'has-error': (!name.valid && name.touched), 'has-success': (name.valid && name.touched)}">
  <label class="col-sm-2 control-label">Name</label>
  <div class="col-sm-10">
    <input [formControl]="name" type="text" class="form-control" placeholder="name"/>
  </div>
</div>

Upvotes: 0

Views: 4567

Answers (2)

abhilash reddy
abhilash reddy

Reputation: 1586

If you would like to create a directive which removes the empty spaces on blur you can use the directive below.

@Directive({
 selector: 'input[type=text]'
 })
export class TrTextTrimDirective {

 constructor(private el: ElementRef, private control: NgControl) {

 }

 @HostListener('blur', ['$event.target.value'])
 onblur(updatedValue: string) {
  let value: any = this.control.control.value;
  if (value != null && typeof value === 'string') {
  value = value.trim();
  this.control.control.setValue(value);
 }
 }
}

Hope this helps.Thank you

Upvotes: 4

LanderV
LanderV

Reputation: 1177

Angular2 generates classes when an input is invalid. You can use these to show your red outline:

input.ng-invalid.ng-dirty {
  outline: 2px solid red;
}

for your validation, you can simply add your own validator:

nospaceValidator(control: AbstractControl): { [s: string]: boolean } {
  let re = / /;
  if (control.value && control.value.match(re)) {
    return { nospace: true };
  }
}

and then use it

'name': ['', Validators.compose([Validators.required, nospaceValidator])],

By the way, you only need Validators.compose when setting multiple validators.

Finally if you want to automatically trim your value or automatically remove spaces from a new value you can use the valueChanges observable of your FormControl

this.name = this.form.controls['name'];

this.name.valueChanges.subscribe((value: string) => {
  console.log('checking value: ', value);
  //do your stuff here
});

alternatively you could also create a directive that doesn't allow you to type a space.

Hope this helps

Upvotes: 3

Related Questions