I would like to avoid white spaces/empty spaces in my angular 2 form? Is it possible? How can this be done?
If you are using Angular Reactive Forms you can create a file with a function - a validator. This will not allow only spaces to be entered. and then in your component typescript file use the validator like this for example.
Pattern Validation with ngModel Suppose we have a regex to validate username as given below. unamePattern = "^[a-z0-9_-]{8,15}$"; To perform validation with ngModel , we will use pattern attribute in following way. Now display validation error message.
Angular uses directives to match these attributes with validator functions in the framework. Every time the value of a form control changes, Angular runs validation and generates either a list of validation errors that results in an INVALID status, or null, which results in a VALID status.
You can create a custom validator to handle this.
new FormControl(field.fieldValue || '', [Validators.required, this.noWhitespaceValidator])
Add noWhitespaceValidator method to your component
public noWhitespaceValidator(control: FormControl) { const isWhitespace = (control.value || '').trim().length === 0; const isValid = !isWhitespace; return isValid ? null : { 'whitespace': true }; }
and in the HTML
<div *ngIf="yourForm.hasError('whitespace')">Please enter valid data</div>
I think a simple and clean solution is to use pattern validation.
The following pattern will allow a string that starts with white spaces and will not allow a string containing only white spaces:
/^(\s+\S+\s*)*(?!\s).*$/
It can be set when adding the validators for the corresponding control of the form group:
const form = this.formBuilder.group({ name: ['', [ Validators.required, Validators.pattern(/^(\s+\S+\s*)*(?!\s).*$/) ]] });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With