I would like to avoid white spaces/empty spaces in my angular 2 form? Is it possible? How can this be done?
To validate white space in starting in an input you can just call change event and do inline function for that.
<input type="text" class="form-control"
placeholder="First Name without white space in starting"
name="firstName"
#firstName="ngModel"
[(ngModel)]="user.FirstName"
(change) ="user.FirstName = user.FirstName.trim()"
required/>
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>
This is a slightly different answer to one below that worked for me:
public static validate(control: FormControl): { whitespace: boolean } {
const valueNoWhiteSpace = control.value.trim();
const isValid = valueNoWhiteSpace === control.value;
return isValid ? null : { whitespace: true };
}
To avoid the form submition, just use required
attr in the input fields.
<input type="text" required>
Or, after submit
When the form is submited, you can use str.trim() to remove white spaces form start and end of an string. I did a submit function to show you:
submitFunction(formData){
if(!formData.foo){
// launch an alert to say the user the field cannot be empty
return false;
}
else
{
formData.foo = formData.foo.trim(); // removes white
// do your logic here
return true;
}
}
i have used form valueChanges function to prevent white spaces. every time it will trim all the fields after that required validation will work for blank string.
Like here:-
this.anyForm.valueChanges.subscribe(data => {
for (var key in data) {
if (data[key].trim() == "") {
this.f[key].setValue("", { emitEvent: false });
}
}
}
Edited --
if you work with any number/integer in you form control in that case trim function will not work directly use like :
this.anyForm.valueChanges.subscribe(data => {
for (var key in data) {
if (data[key] && data[key].toString().trim() == "") {
this.f[key].setValue("", { emitEvent: false });
}
}
}
Prevent user to enter space in textbox in Angular 6
<input type="text" (keydown.space)="$event.preventDefault();" required />