Validating input fields in React TypeScript App using class validator npm package – example code. Validating length and other parameters for input field and making control of form submission.
Install class-validator package NPM command
npm i class-validator
Install class-validator package Yarn command
yarn add class-validator
Class-Validator Example Codes – React TypeScript
import { Length, validate } from 'class-validator';
import { useState } from 'react';
export class Post {
@Length(1, 15)
name!: string;
@Length(1, 25)
address!: string;
}
const [isValid, setIsValid] = useState<boolean>(true);
Example 2:
React Typescript – PhoneNumber Validation Example Code
import React, { useRef, useState } from "react";
import { Length, validate } from "class-validator";
export class Post {
@Length(10, 12)
phoneNumber!: string | null;
}
export InputForm = () => {
const [isValid, setIsValid] = useState<boolean>(true);
const [phoneNo, setPhoneNo] = useState<number>();
const phoneRef = useRef<HTMLInputElement>(null);
const handleValidation = (action: string) => {
let post = new Post();
post.phoneNumber = phoneRef.current && phoneRef.current.value;
validate(post).then((errors) => {
if (errors.length > 0) {
console.log("validation failed. errors: ", errors);
setIsValid(false);
} else {
setIsValid(true);
console.log("validation succeed");
if (action == "submitInput") {
//submit action code
}
}
});
};
return (
<form>
<div>
<label >
Phone number
</label>
<input
type="number"
name="phonenum"
value={phoneNo}
onChange={(event) => {
setPhoneNo(event?.target.value);
handleValidation("changeValue");
}}
id="phone"
ref={phoneRef}
placeholder="Enter Your phone number"
/>
</div>
<span
className={
"flex items-center " +
(isValid ? "hidden" : "")
}
>
* Enter valid phone number !
</span>
<div>
<button
onClick={() => handleValidation("submitInput")}
>
Save
</button>
</div>
</form>
);
}
TypeScript React JS user input field validation example code using class validator npm package. Validating phone number as an example react typescript code.