I would like to avoid white spaces/empty spaces in my angular 2 form? Is it possible? How can this be done?
问题:
回答1:
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));
});
}
回答2:
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>
回答3:
What I did was created a validator that did the samething as angular for minLength except I added the trim()
import { Injectable } from '@angular/core';
import { AbstractControl, ValidatorFn, Validators } from '@angular/forms';
@Injectable()
export class ValidatorHelper {
///This is the guts of Angulars minLength, added a trim for the validation
static minLength(minLength: number): ValidatorFn {
return (control: AbstractControl): { [key: string]: any } => {
if (ValidatorHelper.isPresent(Validators.required(control))) {
return null;
}
const v: string = control.value ? control.value : '';
return v.trim().length < minLength ?
{ 'minlength': { 'requiredLength': minLength, 'actualLength': v.trim().length } } :
null;
};
}
static isPresent(obj: any): boolean {
return obj !== undefined && obj !== null;
}
}
I then in my app.component.ts overrode the minLength function provided by angular
import { Component, OnInit } from '@angular/core';
import { ValidatorHelper } from 'app/common/components/validators/validator-helper';
import { Validators } from '@angular/forms';
@Component({
selector: 'app-root',
templateUrl: './app.component.html'
})
export class AppComponent implements OnInit {
constructor() { }
ngOnInit(): void {
Validators.minLength = ValidatorHelper.minLength;
}
}
Now everywhere angular's minLength built in validator it will use the minLength that you have created in the helper.
Validators.compose([
Validators.minLength(2)
]);
回答4:
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;
}
}
回答5:
Prevent user to enter space in textbox in Angular 6
<input type="text" (keydown.space)="$event.preventDefault();" required />
回答6:
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.
import { AbstractControl } from '@angular/forms';
export function removeSpaces(control: AbstractControl) {
if (control && control.value && !control.value.replace(/\s/g, '').length) {
control.setValue('');
}
return null;
}
and then in your component typescript file use the validator like this for example.
this.formGroup = this.fb.group({
name: [null, [Validators.required, removeSpaces]]
});