How to Validate Octal number in ReactJS?
Last Updated :
30 Sep, 2024
The Octal numeral system is the base-8 number system which uses the digits 0 to 7. It is also known as Oct for short. The following example shows how to validate the user entered data and check whether it is valid or not using the npm module in the ReactJS application.
Approach
To validate octal number in React we will use the validator npm package. We will pass the input number to validator.isOctal function which gives boolean output. If the number is valid the display "Is Octal Number" else return "Is Not Octal Number".
Steps to Create React App and Install Modules
Step 1: Initialize React Application
Create a React application using the following command:
npx create-react-app foldername
Step 2: Switch to the Project Directory
After creating your project folder i.e. foldername, move to it using the following command:
cd foldername
Step 3: Install Required Module
After creating the ReactJS application, Install the validator module using the following command:
npm install validator
Project Structure:
It will look like the following.
Project StructureThe updated dependencies in package.json file are:
"dependencies": {
"@testing-library/jest-dom": "^5.17.0",
"@testing-library/react": "^13.4.0",
"@testing-library/user-event": "^13.5.0",
"react": "^18.3.1",
"react-dom": "^18.3.1",
"react-scripts": "5.0.1",
"validator": "^13.12.0",
"web-vitals": "^2.1.4"
},
Example: This example demonstrates octal number validation with the help of validator npm package.
JavaScript
// Filename - App.js
import React, { useState } from "react";
import validator from "validator";
const App = () => {
const [errorMessage, setErrorMessage] = useState("");
const validate = (value) => {
if (validator.isOctal(value)) {
setErrorMessage("Is Octal Number");
} else {
setErrorMessage("Is Not Octal Number");
}
};
return (
<div
style={{
marginLeft: "200px"
}}
>
<pre>
<h2>Validating Octal Number in ReactJS</h2>
<span>Enter Number: </span>
<input
type="text"
onChange={(e) => validate(e.target.value)}
></input>
<br />
<span
style={{
fontWeight: "bold",
color: "red"
}}
>
{errorMessage}
</span>
</pre>
</div>
);
};
export default App;
Step to Run Application:
Run the application using the following command from the root directory of the project:
npm start
Output:
Validate octal Number