Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 864
MEDHA JHA Avatar asked Dec 30 '25 03:12

MEDHA JHA


1 Answers

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>
like image 87
Sajeetharan Avatar answered Jan 01 '26 19:01

Sajeetharan