MEDHA JHA
MEDHA JHA

Reputation: 31

Angular 6 custom validation to not allow space as the first character?

I am using a reactive textbox, and I need few custom validations for that.

The input box cannot have a character starting with a blank space.

I am using the required validator to make it mandatory, but if I enter a space, it still considers it valid (which I don't want).

How can I fix this from occurring?

Upvotes: 2

Views: 9854

Answers (1)

Sajeetharan
Sajeetharan

Reputation: 222582

You need to create a custom validator to handle this.

new FormControl(field.fieldValue || '', [Validators.required, this.noWhitespace])

Add noWhitespace method to your component/service

public noWhitespace(control: FormControl) {
    let isWhitespace = (control.value || '').trim().length === 0;
    let isValid = !isWhitespace;
    return isValid ? null : { 'whitespace': true }
}

and in the HTML

<div *ngIf="yourForm.hasError('whitespace')">Please enter valid text</div>

Upvotes: 9

Related Questions