I would like to avoid white spaces/empty spaces in my angular 2 form? Is it possible? How can this be done?
In hello.component.html
<input [formControl]="name" />
<div *ngIf="name.hasError('trimError')" > {{ name.errors.trimError.value }} </div>
In hello.component.ts
import { ValidatorFn, FormControl } from '@angular/forms';
const trimValidator: ValidatorFn = (text: FormControl) => {
if (text.value.startsWith(' ')) {
return {
'trimError': { value: 'text has leading whitespace' }
};
}
if (text.value.endsWith(' ')) {
return {
'trimError': { value: 'text has trailing whitespace' }
};
}
return null;
};`
export class AppComponent {
control = new FormControl('', trimValidator);
}
Example Code
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).*$/)
]]
});
To automatically remove all spaces from input field you need to create custom validator.
removeSpaces(c: FormControl) {
if (c && c.value) {
let removedSpaces = c.value.split(' ').join('');
c.value !== removedSpaces && c.setValue(removedSpaces);
}
return null;
}
It works with entered and pasted text.
An alternative would be using the Angular pattern validator and matching on any non-whitespace character.
const nonWhitespaceRegExp: RegExp = new RegExp("\\S");
this.formGroup = this.fb.group({
name: [null, [Validators.required, Validators.pattern(nonWhiteSpaceRegExp)]]
});
Maybe this article can help you http://blog.angular-university.io/introduction-to-angular-2-forms-template-driven-vs-model-driven/
In this approach, you have to use FormControl then watch for value changes and then apply your mask to the value. An example should be:
...
form: FormGroup;
...
ngOnInit(){
this.form.valueChanges
.map((value) => {
// Here you can manipulate your value
value.firstName = value.firstName.trim();
return value;
})
.filter((value) => this.form.valid)
.subscribe((value) => {
console.log("Model Driven Form valid value: vm = ",JSON.stringify(value));
});
}
After lots of trial i found [a-zA-Z\\s]*
for Alphanumeric with white space
Example:
New York
New Delhi