Conoce la importancia de los formularios para tu sitio web

1

Versiones de Angular Forms

2

¿Por qué aprender Angular Forms?

3

Presentación del proyecto: tour por los formularios de Platzi Store

4

Novedades de Angular 10: cómo migrar proyectos de Angular 8 o 9 a la versión 10

Primeros pasos con Angular Forms

5

Template Forms vs. Reactive Forms

6

Dominando el FormControl y sus estados

7

Cómo usar inputs de texto y la importancia del type

8

Manejo y binding de selects y selects múltiples

9

Manejo y binding de inputs radio y checkbox

10

Aplica validaciones a un FormControl

11

Integración y validaciones con CSS para mostrar errores

Descubre todas las validaciones de Angular Forms

12

Usando FormGroup para agrupar multiples campos

13

Reactive Forms con FormBuilder

14

Los 11 validadores de Angular (y expresiones regulares)

15

Manejando múltiples FormsGroups

16

Usando componentes de Angular Material

17

Errores comunes de usabilidad en formularios

18

Validaciones personalizadas: mejorando nuestro formulario de registro

Implemeta validaciones avanzadas en PlatziStore

19

Cómo hacer validaciones grupales en Angular Forms

20

Validaciones condicionadas y reactividad a variaciones en la UI

21

Proyecto: formulario para crear categorías de productos

22

Proyecto: conectando nuestro formulario y la API

23

Proyecto: subir imágenes a Firebase Storage

24

Validaciones asincrónicas

25

PatchValue: crear vs. editar

26

Proyecto: creando el método de editar categorías

Construye formularios dinámicos conectando una API

27

Smart vs. dumb components: un patrón para dividir responsabilidades

28

Implementando smart y dumb components en PlatziStore

29

Proyecto: mejorando nuestro formulario de productos

30

Select dinámico: carga opciones desde una API

31

Select dinámico: trabajando con objetos

32

¿Cómo crear campos on demand? Forms dinámicos con FormArray

Estrategias avanzadas y optimización de formularios

33

Crea tu propia librería de componentes con CVA o Control Value Accesor

34

Crea un buscador de gifs usando la API de Giphy

35

Optimiza un input de búsquedas con RxJS y debounce

36

Examina la accesibilidad de tus formularios

37

Siguientes pasos en tu carrera de desarrollo web profesional con Angular

You don't have access to this class

Keep learning! Join and start boosting your career

Aprovecha el precio especial y haz tu profesión a prueba de IA

Antes: $249

Currency
$209
Suscríbete

Termina en:

2 Días
2 Hrs
42 Min
37 Seg

Validaciones asincrónicas

24/37
Resources

How to perform asynchronous validations on a form?

Asynchronous validations are key to offer a smooth and optimized user experience. Imagine filling out a long form, getting to the end to save the information and surprise! an error appears. This can be frustrating, right? By using asynchronous validations, we can alert the user immediately if the name is already in use, similar to when you create an email on platforms like Hotmail. We will explore the use of an API that checks the availability of categories in real time as the user enters the information.

How does the availability endpoint work?

To perform asynchronous validation, we will use a specific endpoint of our API that checks the availability of a category.

  • Full path: API categories availability
  • Method: POST
  • Functionality: Sends the name of the desired category to be created and returns a JSON with a boolean value indicating whether it is available(true) or not(false).

This is the first step to connect our asynchronous validation with the frontend.

How to implement the validation in the service?

First, we must implement a method in our categories service that connects to the availability endpoint. Here's how to do it:

function checkCategory(name) { return this.http.post('categories/availability', { name });}

This method sends the category name to the endpoint and waits for the availability response. We can specify in the code that we expect a boolean as response.

How to create the validation in validators?

Inside our customvalidators class, we write the asynchronous validation logic. Here we use the power of creating functions within functions, a common practice in languages like JavaScript.

import { map } from 'rxjs/operators';
static validateCategory(service) { return (control) => { const value = control.value; return service.checkCategory(value).pipe( map(response => response.isAvailable ? null : { notAvailable: true }) ); } }}

This code snippet takes the value of the control, checks its availability using the service, and returns null if it is available or an error if it is not. It is essential that you understand how RxJS observables and operators work in order to transform the responses properly.

How to apply validation to the form?

Once our validation is configured, it is time to integrate it with the category form:

this.categoryForm = this.formBuilder.group({ name: [ '', [Validators.required, Validators.minLength(4)], [Validators.validateCategory(this.categoryService)] ] });

We include our synchronous validations first(Validators.required and Validators.minLength), followed by our custom asynchronous validation.

How are errors displayed on the form?

To improve the user experience, we display error messages next to the corresponding field if there is a problem with the validation.

<div*ngIf="form.errors?.notAvailable"> This name is already given to another category.</div>

These messages provide clear and immediate feedback to the user, helping them to correct errors before continuing to complete the form.

We hope you find this approach to implementing asynchronous validations useful in improving your developments. As you gain practice, these techniques will become part of your arsenal of tools for developing dynamic and responsive interfaces. Keep learning and success in your projects!

Contributions 17

Questions 2

Sort by:

Want to see more contributions, questions and answers from the community?

En caso que tengan que usar el tipo “any”, les recomiendo usar “unknown” en su lugar. De esta forma typescript entiende que nunca va a ser un valor “undefined” o “null”.

NO funciona la api

Lo que me gustaria para un futuro curso es ver mas sobre RXJS los operadores map, pipe find, reduce. O existe ya un curso de este tema ???

Para los que estén usando la nueva API [**https://api.escuelajs.co/api/v1:**](https://api.escuelajs.co/api/v1:) No existe el endpoint ***'/categories/availability'*** Pero aun así puedes realizar el ejercicio de la siguiente manera: CategoryService: ```js // Agreguen el import de map de rxjs/operators import { map } from 'rxjs/operators'; checkAvailability(name: Category['name']) { return this.getAll().pipe( map((categories) => { const isAvailable = !categories.some((category) => category.name === name); return isAvailable; }) ); } ```Validators: ```js // Agreguen el import de map de rxjs/operators import { map } from 'rxjs/operators'; static validateCategory(service: CategoriesService) { return (control: AbstractControl) => { const value = control.value; return service.checkAvailability(value).pipe( map((response) => { const isAvailable = response; if (!isAvailable) return { not_available: true }; return null; }) ); }; } ``` Con esto, ya lo demás debería funcionar sin problemas. ***\*Nota: Esto <u>NO</u> es una buena práctica, ya que estamos llamando a nuestro endpoint '/categories' cada vez que cambiamos en el input para validar si existe. Lo mejor es que nuestro backend realice esta operación en la base de datos de forma más eficiente. Esto es solo con fines de realizar el ejercicio para los que quieran ver cómo funciona las validaciones asincrónicas en Angular.*** Espero le sirva a alguien :)

Adjunto evidencia 😅

Hoy 06-01-2022 las consultas a la API arrojan un error en el servidor. Gracias

Si vienes del futuro como yo donde no existe el endpoint donde deben hacerse las peticiones para validar si el nombre existe o no, hagan la petición a el método getAllCategories del archivo de servicios, y el método de los validators debería quedar de la siguiente manera:

 static validateCategory(service: CategoriesService) {
    return (control: AbstractControl) => {
      const value = control.value;
      return service.getAllCategories().pipe(
        map((categories) => {
          const unAvailable = categories.find((category) => category.name === value);
          if (unAvailable === undefined) {
            return null;
          }
          return { not_available: true };
        })
      );
    };
  }

Con eso digamos que el filtrado que se hace en el back lo traemos al front y listo debería funcionar.

El api esta abajo, no responde

Justo este endpoint no existe en la nueva API

Pensando en tener un mejor performance a la hora de hacer las peticiones http agregué dos operadores, sin embargo no funcionó 😦

  • debounceTime se supone que no hace la petición hasta después del tiempo indicado.
  • distinctUntilChanged no debería hacer la petición hasta que lo que escriba el usuario sea distinto en el tiempo dado en dobounceTime
return service.checkCategory(value)
.pipe(
  debounceTime(1000),
  distinctUntilChanged(),
  map((response: Availability) => {
  const isAvailable = response.isAvailable;
  if (!isAvailable) {
    return {not_available: true};
   }
   return null;
  })
);

Muy útiles las validaciones asíncronas, sin embargo noté que cada que escribo una letra en el input se hace una petición al api que configuré

ekisdé

Exelente!! Siempre tuve la duda de como hacer este tipo de validaciones

Excelente las validaciones asíncronas

De las mejores clases de este curso, que manera de darle poder a un formulario con validaciones asincrónicas

xd

consulta si yo tengo un servicio rest, que lo que hace es consulta usuario, pero yo uso para validar si existe el usuario, pero este servicio, su respuesta tiene que llenar algunos datos del formulario.
¿Cual seria la mejor forma de hacerlo?.