validation user input in react js - reactjs

I am trying to figure out how to validate the user's input by checking the length of their input string. Right now the code will validate if the user's input whatever is string or integer. But I need help with validate the length of their input string and give them an error if the length of the input string is less than 2.
const handleText = (event) => {
let letters = /^[A-Za-z]+$/;
if (event.target.value.match(letters)) {
setText(event.target.value);
}else
setText("error");
}
return(
<div>
<TextField onChange = {handleText} label={"Name"}/>
{text}
</div>
);
}

May be this code will help. You can play with it on this link sandbox i created. You can validate length through onSubmit event by using the length property.

Related

How to add a convert a normal string value into a dollar value in react when user is typing

How to change a string value to dollars when user is typing.
Ex:- if the user type something like 5995.
How can I convert this to $59.95 when the user is typing.
And also when the user is saving the value how can I convert it back to a string value and pass it to the back-end.
export const getCurrency = (value) => "$" + (value/100).toFixed(2);
export function convertCurrencyToString(value) {
const removeDollar = value.replace("$", "");
return removeDollar * 100
}
I tried on using these methods to convert it to string and then again convert them to dollars. But this is ok if the value is not changing. But when the value is changing I am getting un-expected errors from the front-end.
as I cant edit the values next to the (.) and etc.
Any suggetions how to fix this issue
You need to remove the dollar sign and the decimal dots on every change of the input field and then re-apply the pattern you want.
See the example below. It is very simple just to show you how it can be done. It lacks the validation of non numeric characters.
const App = (props) => {
var [count, setCount] = React.useState('')
const change = val => {
setCount('$' + (val.replace('$', '').replaceAll('.', '') / 100).toFixed(2))
}
return (
<input value={count} onChange={e => change(e.target.value)} />
)
}
ReactDOM.render(<App/>, document.getElementById("root"))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.14.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.14.0/umd/react-dom.production.min.js"></script>
<div id="root"></div>

How to condition a component to display certain information?

const handleChecked=(e)=>{
setForm({
...form,
[e.target.name]:e.target.checked
})
if(e.target.name == 'lowercase'){
showMinus(longitud)
}
}
const handleSubmit =(e)=> {
updatePassword(longitud)
activeLetters()
e.preventDefault();
}
file 1
const ShowPass =()=>{
let charactersLength = characters.length;
let allChar = ''
for(let i = 0; i<range.current.value; i++){
allChar += characters.charAt(Math.floor(Math.random()* charactersLength))
}
setPassword(allChar)
}
const showMinus=(minusculas)=>{
let allMin=''
let minLong = minusculas.length;
for(let i = 0; i<range.current.value; i++){
allMin += minusculas.charAt(Math.floor(Math.random()* minLong))
}
setMinus(allMin)
}
//¿Que tipo de carcarter es?
const activeLetters =()=>{
let min = ''
for(let i=0;i<characters.length;i++){
let element = characters[i];
if(element === element.toLowerCase() && element !== element.toUpperCase())
min+=element
}
showMinus(min)
}
useEffect(()=>{
getPassLength()
},[])
return(
<>
<div className='classHeader'>
<ShowPassword password={password} icon={<HiOutlineClipboardList/>} />
</div>
<div className='longBox'>
<p>Character Length</p>
<input type="range" min={1} max={16} step={1} ref={range} name="password" ></input>
{long}
</div>
<CapitalLetters
updatePassword={ShowPass}
showMinus={showMinus}
activeLetters={activeLetters}
longitud={long} />
</>
)
Hello everyone, I would like your help please: I am in a situation with the code, what I want to do is the following:
It is a password generator when I give it send
this generates a random password for me when I click the submit button, for this I have created an external component called showPassword that receives a prop called password So, so far so good because I manage to do that, my problem comes in the form file because I have some checkboxes, I want that when push lowercase it sends the password to the screen in only lowercase, that's where my problem is I don't know how to do it,
how do you think i should do it?
So on checkbox click use a state to see whether the ckeckbox is clicked on not. If yes there are js function to convert string to lowercase.
The toLowerCase() method converts a string to lower case letters.
Create a state that will control whether the checkbox is checked or not then inside the props you can create a ternary operator that will send a lowercase if checked or a normal password if not.
<ShowPassword password={isChecked ? password.toLowerCase() : password} icon={<HiOutlineClipboardList/>} />
Hope this works!

React controlled <type='number'> input allows typing in letter?

I am writing an app that contains a controlled input that has the type 'number'. I can still type letters in the input field, but the e.target.value just gets emptied. Does anyone know how I can disable the typing of letters? Namely, if a user types in a letter, the input field will simply not register but still keeps the numbers previously typed in.
Here is my code:
export class AddNewRecipe extends React.Component {
constructor(props){
super(props);
this.state={prepField:{numeral:""}};
this.handleInput = this.handleInput.bind(this)}
handleInput(e){
e.preventDefault();
if(e.target.className =='prepNumber')
{
console.log(e.target.value)
const newPrep = Object.assign({}, this.state.prepField)
newPrep.numeral = currentValue
this.setState({prepField: newPrep})
}
render(){
return (<PrepTime
handlePrep={this.handleInput}
prepField={this.state.prepField}
/>
)
}
and here is the child component
export default function(props){
return(
<div id = 'prepForm'>
<input id = 'prepFormInput' type='number' className='prepNumber' value={props.prepField.numeral} onChange={props.handlePrep} placeholder='prep time' />
</div>
)
}
Does anyone know why that is? Because if I accidentally type '10v', the e.target.value which I will set to my state 'prepField.numeral' just becomes emptied.
Thank you!
You can use this code:
<input id = 'prepFormInput' type='number' className='prepNumber' value={props.prepField.numeral} onChange={props.handlePrep} placeholder='prep time' onkeydown="javascript: return ['Backspace','Delete','ArrowLeft','ArrowRight'].includes(event.code) ? true : !isNaN(Number(event.key)) && event.code!=='Space'" />
This will avoids all characters that are not numbers!
This part make's input accept only numbers:
!isNaN(Number(event.key))
This part make's accept the arrow and delete keys:
['Backspace','Delete','ArrowLeft','ArrowRight'].includes(event.code)
This part make's Firefox disallow spaces in numbers:
event.code!=='Space'
(For react Applications)
If someone has text input and wants to accept only whole numbers. You can use the following code.
const numberInputKeyDown = (event: React.KeyboardEvent<HTMLInputElement>) => {
const eventCode = event.code.toLowerCase();
if (!(event.code !== null
&& (eventCode.includes("digit")
|| eventCode.includes("arrow")
|| eventCode.includes("home")
|| eventCode.includes("end")
|| eventCode.includes("backspace")
|| (eventCode.includes("numpad") && eventCode.length === 7)))
) {
event.preventDefault();
}
};
I have compared the length of eventCode to 7 when it includes numpad because its actual value is like numpad0, numpad1 ... numpad9
This function can be specified in onKeyDown such as
<input
id="myNumberInput"
type="text"
placeholder="numeric input"
onKeyDown={numberInputKeyDown}
/>
To extent field to accept decimals or negative numbers you can console.log the eventCode in numberInputKeyDown to check your required key code and add it in if statement.

Reactjs - input mask without jquery

I'm trying to make an input mask without using jquery. Only using the states of reactjs.
But, whenever he formats the field, I can't erase what was written on it. I will put my code below, in case you have any other way to do this I also accept.
The mask is to be in the format 9999999-9
My code:
const [accountRegex, setAccountRegex] = React.useState('');
function handleAccountRegex(event) {
setAccountRegex(event.target.value)
if (accountRegex.length === 8) {
setAccountRegex(accountRegex.replace(/(\d{7})(\d{1})/g, "$1-$2"))
}
}
<Input name="account" label="Conta" required={true} onChange={handleAccountRegex} value={accountRegex} maxLength='8' />
I've made some changes:
function handleAccountRegex(event) {
// first make sure input doesn't contain the "-" character in it
// because it will mess up the "backspace" key functionality
let val = event.target.value.replace("-", "")
// if input value is 8 digits mask it
if (val.length === 8) {
setAccountRegex(val.replace(/(\d{7})(\d{1})/g, "$1-$2"))
}
// else just store the changes
else setAccountRegex(val)
}

Input validation using pattern attribute in reactjs

i am new to reactjs. I want to validate the input element with pattern attribute (can accept atleast one character) in reactjs. Below is what i have tried doing.
handle_text_input_change = (event) => {
this.props.onChange(event);
console.log("handle",event.target.name);
this.setState({text_input_value: event.target.value});
this.validate(event);
};
validate = (event) => {
let name = event.target.name;
console.log("target name", name);
//const target = event.target;
if (event.target.ValidityState.patternMismatch) {
this.setState({is_valid: false});
this.setState({error: 'Enter the'+ {name} +'with atleast one
character'});
}};
return (
<div>
<input {...rest}
type="text"
onChange={this.handle_text_input_change}
disabled={disabled}
onBlur={this.handle_blur}
onFocus={this.handle_focus}
pattern=".+"
/>
{(valid && active)&& <span className="error">Enter a name</span>}
</div>
);
So this will display the error message when input invalid. However, in the validate method i am checking if input value not null then consider valid. But how can i do input validation using pattern attribute and display error message similarly. Thanks.
Edited: I have tried using html5 validation api as in above code. but then i get the error "Uncaught TypeError: Cannot read property 'valueMissing' of undefined". could someone help me with this. thanks.
You haven't added a value property on your input:
<input {...rest}
type="text"
onChange={this.handle_text_input_change}
disabled={disabled}
onBlur={this.handle_blur}
onFocus={this.handle_focus}
value={this.state.text_input_value}
/>

Resources