How to do Html Form Validation using RxJS

1 minute read

Did you know you can use RxJS simple operators and do html form validation re-actively? Well I learn RxJS operators by implementing them in real world project. In this post I will explain combineLatest operator and its use in real problem solving. 

Sample HTML Form

This is a very simple html form however once you understand the concept you can build any complex form. For now I am sticking with this simple form. Feel free to add more fields on this.

<form action="#">
   First Name: <input type="text" id="firstName">
    <br>
   Last Name: <input type="text" id="lastName">
  </form>
  <div id="message"></div>

Validation Code

I use fromEvent operator to create observable out of input events of text boxes in the form. Next I will use RxJS startWith operator to initialize my observables with empty data. Next I am using RxJS combineLatest operator to create a combination of all of the entries of the form as a single stream of data and doing validation over there to find out is form valid or not.

Finally based on the result I will display form valid true or false in the UI

import { fromEvent, combineLatest } from 'rxjs';
import { map, startWith } from 'rxjs/operators';

const messageElement = document.querySelector('#message'); const
firstNameElement = document.querySelector('#firstName'); const lastNameElement =
document.querySelector('#lastName');

const setMessage = (m) => messageElement.textContent = m;

const firstName$ = fromEvent(firstNameElement, 'input') .pipe( map(e =>
(e.target as any).value), startWith('') );

const lastName$ = fromEvent(lastNameElement, 'input') .pipe( map(e => (e.target
as any).value), startWith('') );

const isFormValid$ = combineLatest(firstName$, lastName$, (firstName: string,
lastName: string) => { return firstName !== '' && lastName !== '' });

isFormValid$.subscribe((isValid) => { setMessage(isValid); })