How to restrict user input to hexadecimal value in React? - javascript

This is my input:
This is its definition:
<Input
// type="number"
id="numeroSerie"
name="num_serie"
defaultValue={this.state.num_serie}
onChange={this.onChange}
required
pattern="[a-fA-F0-9]+"
maxlength="1"
/>;
Using pattern="[a-fA-F0-9]+" means that the user can enter whatever he wants and then the validation will be performed when he clicks on the form submit button.
What I would like is:
When the user clicks on any letter or a number that isn't hexadecimal, the input value would not change. Just like when the input type is number, and the user tries to enter a text.
Is this possible to implement?

To avoid illegal input (the input value would not change):
Add a regex condition inside the handler function would be fine.
/^[0-9a-f]+$/.test(yourValue) // hexadecimal
Test case: hexadecimal: https://www.regextester.com/93640
const {useState} = React;
const App = () => {
const [value, setValue] = useState("");
const onChange = e => {
const input = e.currentTarget.value;
if (/^[0-9a-f]+$/.test(input) || input === "") {
setValue(input);
}
};
return (
<div className="App">
<input
id="numeroSerie"
name="num_serie"
value={value}
onChange={onChange}
/>
</div>
);
}
ReactDOM.render(<App />, document.getElementById("root"));
<div id="root"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.12.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.12.0/umd/react-dom.production.min.js"></script>

This solution uses the onkeyup event of the input element to test the content against an arbitrary regular expression. That means that the input element might momentarily display an illegal character but after the regex test reveals the content to be illegal, the prior contents will be restored. Using the onkeyup event greatly simplifies processing.
function setupField(field, re)
{
field.autocomplete = "off";
field.saveValue = field.value;
field.onkeyup = function() {
var v = field.value;
if (v === '' || re.test(v)) {
field.saveValue = v;
}
else {
field.value = field.saveValue;
}
};
}
setupField(document.getElementById('hex'), /^[A-Fa-f0-9]+$/);
<input type="text" id="hex" size="8">

Related

Results don't show until something is typed into text area

Currently making a small app that translates text to binary or ASCII. I've run into an issue where my code only works if you follow these steps
type something in the text area
choose your language
press the button
I want to make it so I can do it this way as well
choose your language
type something in the text area
press the button
It must have something to do with the message state being undefined if you select a language first.
import { useState, useEffect } from "react";
function Translator() {
const [message, setMessage] = useState("");
const [selectedLanguageResult, setSelectedLanguageResult] = useState("");
const [results, setResults] = useState("");
function handleLanguageSwitch(e) {
let selectedValue = e.target.value;
if (selectedValue === "Ascii") {
setSelectedLanguageResult(translateToAscii());
} else if (selectedValue === "Binary") {
setSelectedLanguageResult(translateToBinary());
}
}
function handleChange(e) {
setMessage(e.target.value);
}
function translateToAscii() {
let arr = [];
for (let i = 0; i < message.length; i++) {
arr.push(message.charCodeAt(i));
}
return arr.join(" ");
}
function translateToBinary() {
let strOut = "";
for (let i = 0; i < message.length; i++) {
strOut += message[i].charCodeAt(0).toString(2) + " ";
}
return strOut;
}
function handleClick(e) {
e.preventDefault();
setResults(selectedLanguageResult);
}
return (
<div className="App">
<form>
<select name="language" onChange={handleLanguageSwitch}>
<option selected disabled>
--Choose language--
</option>
<option value="Ascii">Ascii</option>
<option value="Binary">Binary</option>
</select>
<textarea
type="text"
id="message"
onChange={handleChange}
value={message}
></textarea>
<button onClick={handleClick}>Translate</button>
</form>
<h2>{results}</h2>
</div>
);
}
export default Translator;
You should keep the language in state and set the result when the user submits.
Have a look at this example: https://codesandbox.io/s/flamboyant-bas-wqso2n?file=/src/App.js
I changed the button to a submit button and put the onClick function into the forms onSubmit (this is how a form should be done in react).
I removed selectedLanguageResult in favour of language state.
The select element I used the value prop = language and set the value to your first option as an empty string. React prefers this (you may have noticed a warning in the console).
Finally when the user submits the form, that is where the result is calculated and set.
Hope that makes sense.

How to preserve spacing when storing a string into an array? JavaScript React.js

I have a form with a <textarea>. On submit that string gets stored into an array. Sometimes the strings have blank lines or additional spacing and I want to preserve this spacing. Right now, the only spacing preserved is the spacing between words. The handleSubmit component consist of a useRef hook that is pushed into the array. I'm looking for another approach for storing the string that would preserve spacing. I appreciate all ideas! Thank you for your time!
const textAreaRef = useRef();
const [entryArray, setEntry] = useState([]);
const handleSubmit = (event) => {
event.preventDefault();
const updatedList = [...entryArray];
updatedList.push(textAreaRef.current.value);
textAreaRef.current.value = ""; // Clears value
setEntry(updatedList);
}
return (
<div>
<form class="entryForm" onSubmit={handleSubmit} >
<label for="newEntryId">
<span>New Entry:</span>
<textarea type="text" id="newEntryId" name="newEntryName" rows="30" cols="75"
defaultValue="What's on your mind?" ref = {textAreaRef}
/>
</label>
<button type="submit">Submit</button>
</form>
</div>
)
Can't replicate the issue, works fine.
Vanilla js example, but works the same in React
const area = document.querySelector('textarea')
const button = document.querySelector('button')
const saved = []
button.addEventListener('click', () => {
saved.push(area.value)
area.value = ''
console.log(saved)
})
<textarea></textarea>
<button>save</button>

react input field show the input althogh the user input is not legal, the value suppose to be numeric and the state doesnt change until it is numeric

my input field is showing letters it recieved as inputs althogh its state is not updated due to the test i have at the onchange event.
for example: input field="dldld" and the state will be "".
my onchange function:
const handleChangeAdRentContent = (e) => {
const re = /^[0-9\b]+$/;
if (e.target.min) {
if (e.target.value === "" || re.test(e.target.value)) {
const name = e.target.name;
const value = e.target.value;
setInputAdConentRent({ ...inputAdConentRent, [name]: value });
return;
} else {
return;
}
}
};
this is the input field:
<label
key={masters[index].name + masters[index].adID}
className={notdisplayRent}
>
<span>{masters[index].free_text}</span>
<input
type="text"
name={masters[index].name}
min={masters[index].min_value}
max={masters[index].max_value}
id={masters[index].name}
required={masters[index].required}
value={inputAdConentRent.name}
onChange={handleChangeAdRentContent}
/>
</label>
this is the input it consitst of an object of many inputs controlled by [key,value]
const [inputAdConentRent, setInputAdConentRent] = useState({});
thank you very much

How to validate phone number onClick in React?

I want to validate phone number onClick of a button. This is what I have done, I am new to ReactJS. Please help me in this. When I click submit that time it will show an error message.
const [phoneNo, setPhoneNo] = useState(false)
const [errorMessage, setErrorMessage] = useState("")
const validateFunc = () => {
setPhoneNo(true)
}
const onChangeValidate= (e) => {
var phone = e.target.value;
if( !(phone.match('[0-9]{10}')) ){
setPhoneNo(false);
setErrorMessage("Please enter 10 digit")
}else{
}
setPhoneNo(true)
}
----
<input onChange ={() => onChangeValidate(e)} />
<button onClick = {validateFunc()}>Submit</button>
<p>{errorMessage}</p>
You seem to understand the basic construct of a function component using state but there are a couple of issues.
All event handlers will receive that event as an argument. So you can write <input onChange ={onChangeValidate} /> and <button onClick={validateFunc}>Submit</button>.
It maybe better to use test rather than match in this instance: /[0-9]{10}/.test(phone).
But I also think that you should allow the form to do the validation for you, rather than JS. This way you don't need the error state as the validation is all handled automatically.
Wrap your input and button in a <form> element with its own onSubmit handler, make the input required, and add a type="submit" to the button. You can use CSS to change the style of the input if it's not valid.
const { useState } = React;
function Example() {
const [phoneNo, setPhoneNo] = useState('');
// Update the phone number state when the
// input changes
function handleChange(e) {
setPhoneNo(e.target.value);
}
// In this example prevent the form from
// submitting so we can log the state, but you'll probably
// want to do an AJAX call here to submit the form
function handleSubmit(e) {
e.preventDefault();
console.log(phoneNo);
}
// Add your regex pattern to the input
// and make it required. If you submit an invalid
// number you'll get a neat little tooltip warning
// you of the issue, and the form won't submit until
// it has been fixed
return (
<form onSubmit={handleSubmit}>
<input
pattern="[0-9]{10}"
placeholder="Add a phone number"
onChange={handleChange}
required
/>
<button type="submit">Submit</button>
</form>
);
}
ReactDOM.render(
<Example />,
document.getElementById('react')
);
input:invalid { border: 1px solid red; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.production.min.js"></script>
<div id="react"></div>
const onChangeValidate= (e) => {
var phone = e.target.value;
if( !(phone.match('[0-9]{10}')) ){
setPhoneNo(false);
setErrorMessage("Please enter 10 digit")
}else{
setPhoneNo(true)
}
}
<p>{setPhoneNo===false?errorMessage:''}</p>
Set like these if there will be setphone no false then msg will be shown
Try this!
const [phoneNo, setPhoneNo] = useState(false)
const [errorMessage, setErrorMessage] = useState("")
const validateFunc = () => {
if(phoneNo) {
// perform submittion
}
}
const onChangeValidate= (e) => {
var phone = e.target.value;
if( !(phone.match('[0-9]{10}')) ){
setPhoneNo(false);
setErrorMessage("Please enter 10 digit");
}else{
setPhoneNo(true);
setErrorMessage("");
}
}
----
<input onChange ={(e) => onChangeValidate(e)} />
<button type="button" onClick = {validateFunc()}>Submit</button>
<p>{errorMessage}</p>

React : Display an error message when clicking on the "submit" button if the user enters text

I create a project in React. I would like that when the user clicks on the "submit" button it shows him an error message if in the input "FormDebut" he enters "text" type characters.
But I can't do this :'( , could you help me please? Thanks in advance !
FormulaireReservations.js :
export default function FormulaireReservation() {
return (
<div className="Formulaire">
<Logo/>
<h2><center>Formulaire de réservation</center></h2>
<FormDebut/>
<center><input type="submit" value="Submit" /></center>
</div>
);
}
Component FormDebut.js :
const [value, setValue] = React.useState("");
const onChange = (e) => {
const formattedValue = formatInput(e.target.value);
if (formattedValue.length < 6) {
setValue(formattedValue);
}
}
const formatInput = (input) => {
if (input.length > 2 && input[2] !== ":") {
return input.substring(0, 2) + ":" + input.slice(2);
}
return input;
}
return (
<div className="Form">
<div>Début : </div>
<input placeholder="00:00" type="text" onChange={onChange} value={value}/>
</div>
)
}
export default FormDebut; ```
Test this out in a new document, and then from there you can implement it into your work. You can have a parameter were user has to input a number between 1-10 if they do not then you can display an error message. If number is between 1-10 then you can redirect them. isNAN (is not a number) is a condition and is used for validating the input of the user. The function will check if the input is not a number, it will check if the input is less than 1 or more than 10, if all these conditions are true then it will display an error.
<p>Please input a number between 1 and 10:</p>
<input id="numb">
<button type="button" onclick="myFunction()">Submit</button>
<p id="demo"></p>
<script>
function myFunction() {
// Get the value of the input field with id="numb"
let x = document.getElementById("numb").value;
// If x is Not a Number or less than one or greater than 10
let text;
if (isNaN(x) || x < 1 || x > 10) {
text = "Input not valid";
} else {
text = "Input OK";
}
document.getElementById("demo").innerHTML = text;
}
</script>
I'm not sure if I understood your requirements, but seems that when you click submit button you want to check if the input is numeric value. If that's the case, this should work:
https://codesandbox.io/s/infallible-browser-74r5d7?file=/src/App.js
I moved the value state into the Form itself and passing it as a prop to its child. I also added a new state variable called error that is passed to the FormDebut. On click of the submit button, I strip the : from the value and check if I can parse it to a number. If not, I set the error, otherwise I clear out the error.
Hope that helps
Here is something you can modify your components:
in your FormulaireReservations.js:
export default function FormulaireReservation() {
const [value, setValue] = React.useState("");
const [errorMsg, setErrorMsg] = React.useState("");
const handleSubmission = () => {
if (isNaN(value)) {
setErrorMsg('Input should not be a text')
}
}
React.useEffect(() => {
setErrorMsg('')
}, [value])
return (
<div className="Formulaire">
<Logo />
<h2><center>Formulaire de réservation</center></h2>
<FormDebut value={value} setValue={setValue} msg={errorMsg} />
<center><input type="button" onClick={handleSubmission} value="Submit" /></center>
</div>
);
}
and in your FormDebut.js :
function FormDebut({ value, setValue, msg }) {
const onChange = (e) => {
const formattedValue = formatInput(e.target.value);
if (formattedValue.length < 6) {
setValue(formattedValue);
}
}
const formatInput = (input) => {
if (input.length > 2 && input[2] !== ":") {
return input.substring(0, 2) + ":" + input.slice(2);
}
return input;
}
return (
<div className="Form">
<div>Début : </div>
<input placeholder="00:00" type="text" onChange={onChange} value= {value} />
{ msg && <p>{msg}</p> }
</div>
)}export default FormDebut;
So, basically, the value and errorMsg state is passed to another component that contains the input field. Each time changes on the input field will also update the state declared in the parent component. When a user clicks on submit button, it calls a function that is checking if the value is a number or not. Based on that the errorMsg state is updated. And in the FormDebut component, error msg will be shown just after the input field if any msg was set.

Categories

Resources