0

The user must enter his username in the text field of the form. The accepted username is retrieved from the server and is 'Bret'. But everything the user enters in the field is accepted. How can I solve this problem?

app.component.html

<div id="details">
  <form [formGroup]="form" (ngSubmit)="addDetails()">

    <div class="form-group">

      <label for="s_url">URL:</label>
      <br>
      <input style="width:80%" type="text" id="s_url" formControlName="s_url" />
      <div style="color:red" *ngIf="s_url.value && s_url.invalid">
        not a valid URL
      </div>

    </div>
    <br>
    <button type="submit" [disabled]="form.invalid">Submit</button>
    <br>
    
    <hr>

    Form status: 
    <span [style.color]="form.status === 'VALID' ? 'green' : 'red'">
      {{ form.status }}
    </span>

    <hr>
    <pre>Form values: {{ form.value | json }}</pre>
    <hr>

  </form>
</div>

app.component.ts

import { Component } from '@angular/core';
import { FormGroup, FormBuilder, Validators } from '@angular/forms';
import { RouterModule } from '@angular/router';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
})
export class AppComponent {
  form: FormGroup;

  constructor(private fb: FormBuilder) {
    this.createForm();
  }

  createForm() {
    fetch('https://jsonplaceholder.typicode.com/users')
      .then((response) => response.json())
      .then((json) => {
        console.log(json[0].username);
        this.reg = json[0].username;
      });

    const reg = this.reg;
    this.form = this.fb.group({
      s_url: ['', [Validators.required, Validators.pattern(reg)]],
    });
  }

  // Getter for easy access
  get s_url() {
    return this.form.get('s_url');
  }

  // On submit
  addDetails() {}
}

app.module.ts

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';

import { AppComponent } from './app.component';
import { HelloComponent } from './hello.component';

@NgModule({
  imports:      [ BrowserModule, FormsModule, ReactiveFormsModule ],
  declarations: [ AppComponent, HelloComponent ],
  bootstrap:    [ AppComponent ]
})
export class AppModule { }

Here is the live example: https://stackblitz.com/edit/angular-1kyxry

sp2012
  • 133
  • 8
  • `json` in `.then((json) => { ... }` is not actual [JSON](https://www.json.org/json-en.html). It's an object. So the name of the variable is misleading and the `json` tag wrong. – Andreas Jan 07 '23 at 12:57
  • Your problem is that you have to wait for the async call before you can pass the expected input-value to the validator: [Fixed Stackblitz example](https://stackblitz.com/edit/angular-qqmcej?file=src%2Fapp%2Fapp.component.ts,src%2Fapp%2Fapp.component.html,src%2Fapp%2Fapp.module.ts) – kellermat Jan 07 '23 at 13:05
  • 1
    Thank you @kellermat, your input helped me solve the question. I did as you instructed and demonstrated in the code and I also added code to initialize the form with an empty pattern in the constructor and it worked! – sp2012 Jan 07 '23 at 13:51

0 Answers0