Check password validation in React - javascript

I want to check the validation of Re-password in React, I wrote this code for that but when you set(for Example) passsword:"1234" and Re-password:"1234" it doesn't apply as true but when you enter the fifth character for Re-password it becomes True .
Do you know what is issue?
import React , { Component } from 'react';
export default class RegistrationForm extends Component {
constructor(props) {
super(props);
this.state = {
name: '',
email:'',
password :'',
password_re:'',
password_has_error:false
};
}
checkPassword() {
if(!this.state.password || this.state.password != this.state.password_re) {
this.setState({password_has_error:true});
}
else {
this.setState({password_has_error:false});
}
}
handleChange(event) {
this.setState({[event.target.name] : event.target.value });
if (event.target.name == 'password' || event.target.name == 'password_re')
this.checkPassword();
}
handleSubmit(event) {
event.preventDefault();
// TODO: will submit the form here
}
render(){
return (
<form onSubmit={(event)=>this.handleSubmit(event)}>
<div>
<label>Name</label>
<input
type="text"
name="name"
value={this.state.name}
onChange={(event)=>this.handleChange(event)}
/>
</div>
<div>
<label>Email address</label>
<input
name="email"
type="email"
value={this.state.email}
onChange={(event)=>this.handleChange(event)}
/>
</div>
<div>
<label>Password</label>
<input
type="password"
name="password"
value={this.state.password}
onChange={(event)=>this.handleChange(event)}
/>
</div>
<div>
<label>Re-enter password</label>
<input
type="password"
name="password_re"
value={this.state.password_re}
onChange={(event)=>this.handleChange(event)}
/>
</div>
<button type="submit">Submit</button>
</form>
)
}
}
Edit:This is my React component

This is because, setState is async, it will not update the state value immediately.
Write it like this, by using setState callback method:
handleChange(event) {
const { name, value } = e.target
this.setState({
[name] : value
}, () => {
if (name == 'password' || name == 'password_re')
this.checkPassword();
}
}
);
}
Check this for more details about setState async behaviour.

Related

Check for authentication in react login

I'm trying to set up a hard coded authentication in react when a user logs in through a form. With the code I have right now, it always returns the "else" statement, even if it meets the requirements for the "if".
I'm trying to pass in both the handleSubmit function and the authenticate function in the onClick for the submit button. The other issue I'm running into is that when I pass in both functions, it doesn't reset state on the username and password fields on the form.
import React, { useState } from "react";
import "./Login.css";
function Login() {
const [name, setName] = useState("");
const [uname, setUname] = useState("");
const [pword, setPword] = useState("");
const Employee = {
id: 12345,
password: "abcde",
};
function handleInput(e) {
setName(e.target.value);
}
function handleSubmit(e) {
e.preventDefault();
setUname("");
setPword("");
}
function authenticate() {
if (uname === Employee.id && pword === Employee.password) {
console.log("Success! Logged in.");
} else {
console.log("Invalid Employee ID and/or password");
}
}
return (
<div className="login-card">
Hello {name}
<div className="username" onChange={handleInput}>
<input
type="input"
className="username-input"
placeholder="Employee ID"
onChange={(e) => setUname(e.target.value)}
value={uname}
autoComplete="off"
/>
</div>
<div className="password">
<input
className="password-input"
type="password"
placeholder="Password"
onChange={(e) => setPword(e.target.value)}
value={pword}
autoComplete="off"
/>
</div>
<button
className="submit-btn"
type="submit"
onClick={(handleSubmit, authenticate)}
>
Login
</button>
</div>
);
}
export default Login;
EDIT: A combination of all three answers worked. Had to wrap the div in a form, call the authenticate function inside of handleSubmit, and use "==" instead of "===" on checking for the Employee.id:
import React, { useState } from "react";
import "./Login.css";
function Login() {
const [name, setName] = useState("");
const [uname, setUname] = useState("");
const [pword, setPword] = useState("");
const Employee = {
id: 12345,
password: "abcde",
};
function handleInput(e) {
setName(e.target.value);
}
function authenticate() {
if (uname == Employee.id && pword === Employee.password) {
console.log("Success! Logged in.");
} else {
console.log("Invalid Employee ID and/or password");
}
}
function handleSubmit(e) {
authenticate();
e.preventDefault();
setUname("");
setPword("");
}
return (
<div className="login-card">
Hello {name}
<form onSubmit={handleSubmit}>
<div className="username" onChange={handleInput}>
<input
type="input"
className="username-input"
placeholder="Employee ID"
onChange={(e) => setUname(e.target.value)}
value={uname}
autoComplete="off"
/>
</div>
<div className="password">
<input
className="password-input"
type="password"
placeholder="Password"
onChange={(e) => setPword(e.target.value)}
value={pword}
autoComplete="off"
/>
</div>
<button className="submit-btn" type="submit" onClick={handleSubmit}>
Login
</button>
</form>
</div>
);
}
export default Login;
import React, { useState } from "react";
function Login() {
const [name, setName] = useState("");
const [uname, setUname] = useState("");
const [pword, setPword] = useState("");
const Employee = {
id: "12345", //string
password: "abcde"
};
function handleInput(e) {
setName(e.target.value);
}
function handleSubmit(e) {
e.preventDefault();
setUname("");
setPword("");
}
function authenticate(e) {
if (uname === Employee.id && pword === Employee.password) {
console.log("Success! Logged in.");
} else {
console.log("Invalid Employee ID and/or password");
}
handleSubmit(e);
}
console.log(uname, pword);
return (
<div className="login-card">
Hello {name}
<div className="username" onChange={handleInput}>
<input
type="input"
className="username-input"
placeholder="Employee ID"
onChange={(e) => setUname(e.target.value)}
value={uname}
autoComplete="off"
/>
</div>
<div className="password">
<input
className="password-input"
type="password"
placeholder="Password"
onChange={(e) => setPword(e.target.value)}
value={pword}
autoComplete="off"
/>
</div>
<button className="submit-btn" type="submit" onClick={authenticate}>
Login
</button>
</div>
);
}
export default Login;
You are trying to compare id which is number but e.target.value always return string.So === does strict checking with value as well as its type and it fails since "12345" === 12345 will be false.
you need to place those divs inside a form tag
then you can assign "onSubmit" to the form
and also you can do all in one function you don't need two
try this and tell me if its works:
function handleSubmit = (e) => {
e.preventDefault();
if(uname === Employee.id && pword === employee.password){
console.log("logged in")
setname(uname);
setUname("")
setPword("")
} else if(!uname && !pword){
console.log("please fill the fields")
}
else {
console.log("invalid login");
setUname("")
setPword("")
}
}
<div className="login-card">
Hello {name}
<form onSubmit={handleSubmit}>
<div className="username">
<input
type="input"
className="username-input"
placeholder="Employee ID"
onChange={(e) => setUname(e.target.value)}
value={uname}
autoComplete="off"
/>
</div>
<div className="password">
<input
className="password-input"
type="password"
placeholder="Password"
onChange={(e) => setPword(e.target.value)}
value={pword}
/>
</div>
<button type="submit">submit</button>
</form>
</div>
</div>

Reset form input values in React

I want create a function using with i can reset value in form inputs without submit. I tried create that function in App Component (resetFormFields) and pass it on props to Form Component. It's preety simply when I want to do this onSubmit (e.target.reset()) but I got stuck when I have to do it without submit, on a different element than the form. Can I do that without adding these values to state?
App:
class App extends Component {
state = {
people: [],
formMessages: [],
person: null
};
handleFormSubmit = e => {
e.preventDefault();
const form = e.target;
const name = form.elements["name"].value;
const username = form.elements["username"].value;
this.addPerson(name, email);
form.reset();
};
resetFormFields = () => {
return;
}
render() {
return (
<div className="App">
<Form formSubmit={this.handleFormSubmit}
reset={this.resetFormFields} />
</div>
);
}
Form:
const Form = props => (
<form className={classes.Form}
id="form"
onSubmit={props.formSubmit}>
<input autoFocus
id="name"
type="text"
defaultValue=""
placeholder="Name..."
/>
<input
id="email"
type="text"
defaultValue=""
placeholder="Email..."
/>
<Button
btnType="Submit"
form="form"
type='submit'>
Submit
</Button>
<label onClick={props.reset}>Reset fields</label>
</form> );
onHandleFormSubmit = (e) =>{
e.preventDefault();
e.target.reset();
}
You need to make your inputs controlled by passing the value you store in your state then you just have to reset the state values and your component value resets.
check this sample below
handleInputChange = (e) => {
let { name, value } = e.target;
this.setState({
...this.state,
inputs: {
[name]: value
}
});
}
your component will now look like
<input name='fullName' value={this.state.inputs.fullName} onChange={this.handleInputChange} />
Your reset function will just clear the state and your input field will be empty since it's controlled via state
resetInputFields = () => {
this.setState({ inputs: {} })
}
you should give set your input values based on component state, then just update the component state
class App extends Component {
state = {
people: [],
formMessages: [],
person: null,
name: "",
email: "",
};
updateState = (newState) => {
this.setState(newState);
}
handleFormSubmit = e => {
e.preventDefault();
this.addPerson(this.state.name, this.state.email);
form.reset();
};
resetFormFields = () => {
this.setState({name:"", email: ""});
}
render() {
return (
<div className="App">
<Form formSubmit={this.handleFormSubmit} updateState={this.updateState}
reset={this.resetFormFields} email={this.state.email} name={this.state.name} />
</div>
);
}
and then
const Form = props => (
<form className={classes.Form}
id="form"
onSubmit={props.formSubmit}>
<input autoFocus
id="name"
type="text"
defaultValue=""
value={this.props.name}
onChange={(e) => this.props.updateState({name: e.target.value})}
placeholder="Name..."
/>
<input
id="email"
type="text"
defaultValue=""
value={this.props.email}
onChange={(e) => this.props.updateState({email: e.target.value})}
placeholder="Email..."
/>
<Button
btnType="Submit"
form="form"
type='submit'>
Submit
</Button>
<label onClick={props.reset}>Reset fields</label>
</form> );

How to get data from multiple inputs and put it to the localStorage? React

class Register extends Component{
constructor(props) {
super(props);
this.submit = this.submit.bind(this);
}
submit(event) {
let username = document.getElementById('username');
let usernameValue = username.value;
localStorage.setItem('username', usernameValue);
}
render(){
return(
<div className="register-block">
<h4>Register</h4>
<div className="register-block">
<InputGroup>
<Input id="username" placeholder="username" />
<Input id="password" placeholder="password" />
<Input id="tel" placeholder="tel number" />
</InputGroup>
</div>
<Button color="primary" onClick ={this.submit}>Register</Button>
</div>
)
}
}
//At this point, I can put data only from input id="username". How can I get data from others inputs and store it in localStorage? Its educational project
You can do something like this:
let username = document.getElementById('username').value;
let password = document.getElementById('password').value;
let phone = document.getElementById('tel').value;
let data = [];
data['username'] = username;
data['password '] = password;
data['phone '] = phone;
localStorage.setItem('userdata', JSON.stringify(data));
// To retrieve data try this
data = JSON.parse(localStorage.getItem('userdata'));
First of all directly interacting with the DOM node in react is not a good idea. Secondly, You can make all your Inputs to be controlled and push the data in localStorage on submit like
class Register extends Component{
constructor(props) {
super(props);
this.submit = this.submit.bind(this);
this.state={
username: '',
password: '',
tel: ''
}
}
handleChange = (key, val) => {
this.setState({[key]: val})
}
submit(event) {
localStorage.setItem('registerData', JSON.stringify(this.state));
}
render(){
return(
<div className="register-block">
<h4>Register</h4>
<div className="register-block">
<InputGroup>
<Input id="username" placeholder="username" onChange={(val) => this.handleChange('username', val)} />
<Input id="password" placeholder="password" onChange={(val) => this.handleChange('password', val)}/>
<Input id="tel" placeholder="tel number" onChange={(val) => this.handleChange('tel', val)} />
</InputGroup>
</div>
<Button color="primary" onClick ={this.submit}>Register</Button>
</div>
)
}
}
Assuming your Input is a custom component, you must also look into How to pass data from child to parent component. Also check Controlled Vs UnControlled Components in React

Slack invite with react and slack api

I am attempting to set up a slack invite based on this tutorial: https://www.robinwieruch.de/slack-invite-javascript-react
I have everything set up the same as the example but I'm getting this error
TypeError: onUserAuthSignUp is not a function
I can see in the code where it's being destructured:
const { onUserAuthSignUp } = this.props
But I cannot see what I'm missing, i'm still learning JS and React so i'm thinking it's something really obvious.
Full code for the form is below, <Form /> is then imported into the index.js file.
// Form.js
import React, { Component } from "react"
import axios from 'axios';
var SLACK_TOKEN = 'slack-token';
var SLACK_INVITE_ENDPOINT = 'https://slack.com/api/users.admin.invite';
function inviteSuccess() {
console.log('success');
}
function inviteError() {
console.log('error');
}
function inviteToSlack(email) {
var QUERY_PARAMS = `email=${email}&token=${SLACK_TOKEN}&set_active=true`;
axios.get(`${SLACK_INVITE_ENDPOINT}?${QUERY_PARAMS}`)
.then(inviteSuccess)
.catch(inviteError);
}
export class Form extends Component {
constructor(props) {
super(props);
this.state = {
email: '',
passwordOne: '',
passwordTwo: '',
username: '',
isSlackInvite: true,
};
this.onSubmit = this.onSubmit.bind(this);
this.onCheckSlackInvite = this.onCheckSlackInvite.bind(this);
}
onCheckSlackInvite(e) {
this.setState(prevState => ({ isSlackInvite: !prevState.isSlackInvite }));
}
onSubmit(e) {
e.preventDefault();
const {
email,
passwordOne,
username,
isSlackInvite,
} = this.state;
const { onUserAuthSignUp } = this.props;
if (isSlackInvite) {
inviteToSlack(email);
}
onUserAuthSignUp(email, passwordOne, username);
}
render() {
const {
email,
passwordOne,
passwordTwo,
username,
isSlackInvite,
} = this.state;
return (
<form onSubmit={this.onSubmit}>
<input
type="text"
placeholder="Full Name"
value={username}
onChange={e => this.setState({ username: e.target.value})}
/>
<input
type="text"
placeholder="Email Address"
value={email}
onChange={e => this.setState({ email: e.target.value})}
/>
<input
type="password"
placeholder="Password"
value={passwordOne}
onChange={e => this.setState({ passwordOne: e.target.value})}
/>
<input
type="password"
placeholder="Confirm Password"
value={passwordTwo}
onChange={e => this.setState({ passwordTwo: e.target.value})}
/>
<div>
<label>Join Slack Group</label>
<input
type="checkbox"
checked={isSlackInvite}
onChange={this.onCheckSlackInvite}
/>
</div>
<button
disabled={passwordOne !== passwordTwo || passwordOne === '' || username === ''}
type="submit"
className="btn"
>
Sign Up
</button>
</form>
)
}
}
Tutorial author here. Sorry for being unclear in the tutorial!
The SignUp component only showcases how it can be used afterward (e.g. in a sign up process). But it doesn't show how to implement the whole sign up, it merely shows how the Slack invite can be used as an opt-in in such a form:
if (isSlackInvite) {
inviteToSlack(email);
}
If you are curious to implement the whole sign up process, checkout the Complete Firebase in React authentication tutorial. There you will implement the SignUp form where you can opt-in the Slack invite afterward.

input field not changing in React (controlled input)

Without the bind.(this) on the this.updateEmail.bind(this) the input field value changes but I receive in error saying cannot set this.setState of undefind. So I add .bind(this) but it doesn't work at all.. a bit confused
import React, { Component } from 'react';
import Request from 'superagent';
class App extends Component {
constructor(){
super()
this.state = {
email: 'asdf',
password: ''
}
}
updateEmail(e){
this.setState={
email: e.target.value
}
}
createUser(e){
var query = 'star';
e.preventDefault()
console.log(this.state.email)
var url = `http://www.omdbapi.com?s=${query}&y=&r=json&plot=short`;
Request.get(url).then((response) => {
console.log(response)
this.setState({
movies: response.body.Search,
total: response.body.totalResults
});
});
}
render() {
return (
<div className="App">
<div className="App-header">
<form onSubmit={this.createUser.bind(this)}>
<input type="text"
name="email"
onChange={this.updateEmail.bind(this)}
value={this.state.email}
placeholder="email"/>
<br/>
<input type="text"
name="password"
value={this.state.password}
onChange={this.updatePassword}
placeholder="password"/>
<br/>
<input type="submit" value="submit"/>
</form>
</div>
</div>
);
}
}
export default App;
setState is a function, you should call it as such:
this.setState({ foo: 'bar' });

Categories