Input validation using pattern attribute in reactjs - 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}
/>

Related

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.

validation user input in react js

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.

How can I update the correct field when the user can type either a username or an email?

I'm working on an app in rails using react/redux, and I have one text box that can accept either a username or a email. With the help of the post below, I tried the solution of adding another function to handle the email/username input. But it seems that now I'm unable to type the # character into the text box (and it seems that the # character is getting appended to whatever I type in for the nickname and being set as the user's email). What is the correct way to do this kind of filtering?
Update: I've narrowed the problem down to my handleLoginInput function, specifically the first line that is setting the field variable; the logic makes sense to me, but for some reason I can't type # in the text field, which makes it unable to save the value to the correct field. But when I comment out the let field=... and manually put in the username field for the field variable in the this.setState... line below it, it works (for setting the username field); however, when I try doing the same for the email field, I'm unable to type in the text box at all.
handleLoginInput(e) {
let field = e.currentTarget.value.includes('#') ? 'email' : 'username';
this.setState({ [field]: e.currentTarget.value });
}
// in my form
<label>
<input type="text"
value={ this.state.username }
onChange={ e => this.handleLoginInput(e) }
className="login-input"
placeholder={ formType === 'Log In' ? "Email address or username" :
"Email" }
/>
</label>
You cannot use onChange that way, you need to setState first
handleLoginValue(e) {
let field = e.currentTarget.value.includes('#') ? 'email' : 'username'
this.setState({[field]: e.currentTarget.value});
}
//render
<input type="text"
value={this.state.username}
onChange={e => this.handleLoginValue(e)}
className="login-input"
placeholder={formType === 'Log In' ? "Email address or username" : "Email"}
/>
<button onClick={this.onSubmit}>
Submit
<button>

How do I autosubmit text after entry?

I was wondering what's the best approach for handling an autosubmit of a code that a user types in? I have this so far but idk if this works. I tried testing it but I wasn't performing as I expected.
This is the form control:
<div className="form-group">
<input
type="tel"
autoComplete="one-time-code"
maxLength="6"
className="code-form"
onChange={this.changeCode}
value={code}
/>
</div>
And this is the onChange event:
changeCode = e => {
this.setState({ code: e.target.value });
if(this.verificationCode.length == 6) {
this.verifyCode();
}
};
If the length of what the user types in is 6, then I just want to submit it. Is this right approach?
The following code is inside a webview react project that is housed inside of react-native app.
There is no need to use debouncing for such small task,just check lenght of code in setState's call back and submit.
changeCode = e => {
this.setState({ code: e.target.value },()=>{
if(this.state.code.length == 6) {
this.verifyCode();
}
});
};
You can try with throttle and debounce:
if (this.verificationCode.length < 5) {
throttle(500, this.verifyCode)
} else {
debounce(500, this.verifyCode);
}

Resources