Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to trim values from Angular form?

I have an Angular form with two inputs, username and password, when the user submits the form the values are sent with POST to a Spring Boot REST Controller. I want to trim the datas before they are sent to the controller but I can't find how to do it.

This is my form-component.html:

    <form  #loginForm="ngForm" (ngSubmit)="onSubmit()" name="loginForm">
        <input required ngModel [(ngModel)]="user.username" name="loginUsername" #loginUsername="ngModel" type="text" placeholder="Username">
        <div class="alert alert-danger" role="alert" *ngIf="loginUsername.invalid && (loginUsername.dirty || loginUsername.touched)">Username not inserted</div>
        <input required ngModel [(ngModel)]="user.password" name="loginPassword" #loginPassword="ngModel" type="text" placeholder="Password">
        <div class="alert alert-danger" role="alert" *ngIf="loginPassword.invalid && (loginPassword.dirty || loginPassword.touched)">Password not inserted</div>
        <button class="btn btn-primary" type="submit">Login</button>
    </form>

This is my form-component.ts:

export class LoginFormComponent implements OnInit{

  user: User;

  constructor(private route: ActivatedRoute, 
    private router: Router, 
      private login: LoginService){
    this.user = new User();
  };

  ngOnInit(): void { };

  onSubmit() {
    this.login.send(this.user).subscribe(result => this.router.navigate(['/http://localhost:8080/login']));
  }

}

This is my user.ts:

export class User {

    username: string;
    password: string;

    constructor(){
        this.username = "";
        this.password = "";
    }
    
}

This is my login-service.ts:

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { User } from '../classes/user';

@Injectable({
  providedIn: 'root'
})
export class LoginService {

  private loginUrl: string;

  constructor(private http: HttpClient) {
    this.loginUrl = 'http://localhost:8080/login';
   }

   public send(user: User) {
    return this.http.post<User>(this.loginUrl, user);
  }
}

This is my Spring REST controller:

@EnableDiscoveryClient
@SpringBootApplication
@RestController
@RequestMapping
@CrossOrigin(origins = "http://localhost:4200")
public class ApiGatewayApplication {

    public static void main(String[] args) {
        SpringApplication.run(ApiGatewayApplication.class, args);
    }

    @PostMapping("/login")
    public void postUser(@RequestBody User user) {
        System.out.println("Username:" + user.getUsername());
        System.out.println("Password:" + user.getPassword());
    }
}
like image 211
Luca Avatar asked Nov 16 '25 03:11

Luca


1 Answers

you can use reactive forms to handle your form, it's much simpler to deal with forms.

It will look like this:

form-component.html:

<form  [formGroup]="loginForm" (ngSubmit)="onSubmit()" name="loginForm">
        <input required name="loginUsername" type="text" placeholder="Username" formControlName="username">
        <div class="alert alert-danger" role="alert" *ngIf="!formGroup.get('username').valid formGroup.get('username').touched)">Username not inserted</div>
        <input required name="loginPassword" type="text" placeholder="Password" formControlName="password">
        <div class="alert alert-danger" role="alert" *ngIf="!formGroup.get('password').valid formGroup.get('password').touched)">Password not inserted</div>
        <button class="btn btn-primary" type="submit">Login</button>
    </form>

form-component.ts:

    import { FormGroup, FormControl } from '@angular/forms';
        export class LoginFormComponent implements OnInit{
        
          user: User;
loginForm = new FormGroup({
    username: new FormControl('', [TrimFormControl]),
    password: new FormControl('', [TrimFormControl]),
  });
        
          constructor(private route: ActivatedRoute, 
            private router: Router, 
              private login: LoginService){
            this.user = new User();
          };
        
          ngOnInit(): void { };
        
          onSubmit() {
            this.login.send(this.loginForm. getRawValue()).subscribe(result => this.router.navigate(['/http://localhost:8080/login']));
          }
        
        }

And then you can create a custom validator that trims automatically your inputs.

The custom validator:

export class TrimFormControl extends FormControl {
    private _value!: string | null;

    get value(): string | null {
        return this._value;
    }

    set value(value: string | null) {
        this._value = value ? value.trim() : value;
    }
}

You put it in the array, on the form group creation above. It's also a good practice to use reactive form in angular, it easier for you to handle verification in the form, and also very useful to use a same form, to create and update. (You can populate the input when you create the form group, the empty string mean that the inputs are empty).

like image 110
Filipe Doutel Silva Avatar answered Nov 17 '25 20:11

Filipe Doutel Silva



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!