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 });
}
}
}
I had a requirement where in the Firstname and Lastname are user inputs which were required fields and user should not be able to hit space as the first character.
Import AbstractControl from node_modules.
import { AbstractControl } from '@angular/forms';
check if the first character is space
If yes then blank the value and return required: true.
If no return null
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/>
I am late to the party, but I found most answers not fully functional for my use case. I am using regular expression matching, which detects UTF 8 Whitespace correctly (.trim() does not). Additionally I added a null value check. Code is typescript but should be easy to convert to javascript.