Angular表单提交前如何对表单字段值进行trim去空格处理?
实现方案
下面提供4种不同适用场景的实现方式,可根据需求选择:
方案1:最简快速实现(仅当前表单适用)
直接修改提交逻辑,在发送请求前对用户输入字段做trim处理,修改form-component.ts的onSubmit方法即可:
onSubmit() { // 处理去空格 this.user.username = this.user.username.trim(); this.user.password = this.user.password.trim(); this.login.send(this.user).subscribe(result => this.router.navigate(['/http://localhost:8080/login'])); }
方案2:全局通用方案(所有表单自动生效)
自定义Angular trim指令,所有文本输入框可复用,无需每个提交逻辑手动写trim:
- 生成指令:执行
ng generate directive directives/trim - 编写指令代码:
import { Directive, HostListener, ElementRef } from '@angular/core'; import { NgControl } from '@angular/forms'; @Directive({ selector: '[appTrim]' }) export class TrimDirective { constructor(private el: ElementRef, private control: NgControl) {} // 失焦时自动去空格 @HostListener('blur') onBlur() { const value = this.el.nativeElement.value; this.control.control.setValue(value.trim()); } // 输入时实时过滤首尾空格(可选) @HostListener('input') onInput() { const value = this.el.nativeElement.value; if (value.startsWith(' ') || value.endsWith(' ')) { this.control.control.setValue(value.trim(), { emitEvent: false }); } } }
- 将该指令添加到对应模块的
declarations数组中 - 在表单的input标签上添加
appTrim属性即可:
<input required ngModel [(ngModel)]="user.username" name="loginUsername" #loginUsername="ngModel" type="text" placeholder="Username" appTrim> <input required ngModel [(ngModel)]="user.password" name="loginPassword" #loginPassword="ngModel" type="text" placeholder="Password" appTrim>
方案3:服务层统一处理(所有调用登录接口的场景生效)
修改login-service.ts的send方法,发送请求前统一对入参做trim处理:
public send(user: User) { const trimmedUser = { username: user.username.trim(), password: user.password.trim() }; return this.http.post<User>(this.loginUrl, trimmedUser); }
方案4:后端双重校验(避免前端校验被绕过)
建议后端也加一层trim处理,防止有请求绕开前端直接调用接口,可选择两种实现:
方式1:接口内手动处理
@PostMapping("/login") public void postUser(@RequestBody User user) { String username = user.getUsername().trim(); String password = user.getPassword().trim(); System.out.println("Username:" + username); System.out.println("Password:" + password); }
方式2:全局自动反序列化trim
给Java的User类的属性添加Jackson注解,Spring反序列化时自动去掉空格:
@JsonDeserialize(using = StringTrimmerDeserializer.class) private String username; @JsonDeserialize(using = StringTrimmerDeserializer.class) private String password;
内容的提问来源于stack exchange,提问作者Luca
相关产品推荐
相关产品推荐

