I am validating some details, the problem is when the validation is complete and I want to move to the next page with submit, the first time it's receiving the data, and the second time it's checking if the data is true and moves me to the next page.
I have tried to put all the validation process to the OnChange function, but it messes up all of the validation process, I have also tried to put the error variables to the state but I receive an error message that It's constant variables and can't be changed.
import { Link } from 'react-router-dom';
class Profile extends Component {
state = {
details: {
firstName: '',
lastName: '',
id: '',
email: ''
},
error: false,
complete: false
};
OnSubmit = e => {
e.preventDefault();
let re = /^(([^<>()\[\]\\.,;:\s#"]+(\.[^<>()\[\]\\.,;:\s#"]+)*)|(".+"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
const { email } = this.state.details;
const { firstName } = this.state.details;
const { lastName } = this.state.details;
const { id } = this.state.details;
let errorid = false;
let errorfirstlast = false;
let erroremail = false;
if (id.length <= 9 && id !== '') {
console.log('trueid');
errorid = false;
} else {
errorid = true;
console.log('falseid');
}
if (re.test(email)) {
console.log('trueemail');
erroremail = false;
} else {
erroremail = true;
console.log('falseemail');
}
if (
firstName !== '' &&
lastName !== '' &&
firstName.substr(0, 1) === firstName.substr(0, 1).toUpperCase() &&
lastName.substr(0, 1) === lastName.substr(0, 1).toUpperCase() &&
!firstName.match(/\d/) &&
!lastName.match(/\d/)
) {
console.log('truefirstlast');
errorfirstlast = false;
} else {
errorfirstlast = true;
console.log('falsefirstlast');
}
if (erroremail === true || errorfirstlast === true || errorid === true) {
this.setState({ error: true });
} else {
this.setState({ error: false });
this.setState({ complete: true });
}
};
OnChange = e => {
e.preventDefault();
this.setState({
details: { ...this.state.details, [e.target.name]: e.target.value }
});
};
render() {
return (
<div>
<div className="container text-center mt-4" style={{ width: '500px' }}>
<form className="px-4 py-3" onSubmit={this.OnSubmit}>
<div className="form-group">
{this.state.error === true ? (
<p className="text-danger">
Some of the details are wrong check the fields above
</p>
) : null}
<label>First Name:</label>
<input
type="text"
className="form-control"
onChange={this.OnChange}
name="firstName"
/>
</div>
<div className="form-group">
<label>Last Name:</label>
<input
type="text"
className="form-control"
onChange={this.OnChange}
name="lastName"
/>
</div>
<div className="form-group">
<label>ID Number:</label>
<input
type="text"
className="form-control"
onChange={this.OnChange}
name="id"
/>
</div>
<div className="form-group">
<label>Email:</label>
<input
type="text"
className="form-control"
onChange={this.OnChange}
name="email"
/>
</div>
{this.state.complete === true ? (
<Link to="/success">
<button type="submit" className="btn btn-secondary mt-3">
Check
</button>
</Link>
) : (
<button type="submit" className="btn btn-secondary mt-3">
Check
</button>
)}
</form>
</div>
</div>
);
}
}
export default Profile;
The problem is that I enter the next page with the second click on the submit button, I want to enter with the first try
The reason is that this.setState(..) is an async function Reference here.
Moreover you're calling multiple state-operations behind each other instead of putting it in one call like:
if (erroremail === true || errorfirstlast === true || errorid === true) {
this.setState({ error: true });
} else {
this.setState({
error: false,
complete: true
});
}
If you want to to an action after this state operation is done you can add a callback to the operation:
if (erroremail === true || errorfirstlast === true || errorid === true) {
this.setState({ error: true });
} else {
this.setState({
error: false,
complete: true
}, this.submitMyStuff);
}
const submitMyStuff = () => {
// submit all my stuff
}
Related
I am using a Latest Version of Linux
login.jsx
import React, { Component } from "react";
import Input from "./common/input";
class Login extends Component {
state = {
account: {
username: "",
password: "",
},
errors: {},
};
validate = (input) => {
const errors = {};
const { account } = this.state;
if (account.username.trim() === "") {
errors.username = "Username is Required";
}
if (account.password.trim() === "") {
errors.password = "Password is Required";
}
return Object.keys.length === 0 ? null : errors;
};
handleSubmit = (e) => {
e.preventDefault();
const errors = this.validate();
// console.log(errors);
this.setState({ errors: errors || {} });
if (errors) return;
// Call the Server
console.log("Submitted");
};
validateProperty = ({ name, value }) => {
if (name === "username") {
if (value.trim === "") return "Username is Required";
}
if (name === "password") {
if (value.trim === "") return "Password is Required";
}
};
handleChange = ({ currentTarget: input }) => {
const errors = { ...this.state.errors };
const errorMessage = this.validateProperty(input);
console.log(errorMessage);
if (errorMessage) errors[input.name] = errorMessage;
else delete errors[input.name];
const account = { ...this.state.account };
account[input.name] = input.value;
this.setState({ account, errors });
};
render() {
const { account, errors } = this.state;
return (
<div className="container ">
<div className="row justify-content-center">
<div className="col-md-6">
<div className="card mt-5">
<div className="card-header">
<h1 className="text-center">Login</h1>
</div>
<div className="card-body">
<form onSubmit={this.handleSubmit}>
<Input
name="username"
value={account.username}
onChange={this.handleChange}
label="Username"
type="text"
error={errors.username}
/>
<Input
name="password"
value={account.password}
onChange={this.handleChange}
label="Password"
type="password"
error={errors.password}
/>
<div className="text-center">
<button className="btn btn-primary">Log in</button>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
);
}
}
export default Login;
On top i have a function called validateProperty this function returns undefined I need your help Guys
I print the function in also console it return a undefined what can i do ?
Thanks in Advance <3
I print the function in also console it return a undefined what can i do ?
Thanks in Advance <3
When the function will return undefined?
You probably wanted this:
return Object.keys(errors).length === 0 ? null : errors
Because
Object.keys.length
is always equal 1
I have created the following UI:
Initially I want Movie Name, Ratings and Durations column to have a black border while if a user enters an invalid input (or empty), it should be red. As you can see, Ratings is still red despite the fact that the page has just refreshed. It should be black like its siblings. Can anyone point out why is this happening? Perhaps there is a different way to handle validations in React because of state hooks?
Initial State:
const [validations, setValidations] = useState({
isNameValid: true,
isRatingValid: true,
isDurationValid: true,
});
Submit form if it's valid:
const handleFormSubmit = (event) => {
event.preventDefault();
if (validateInput(newMovie)) {
props.onSubmit(newMovie);
setNewMovie(emptyObject);
}
};
CSS Rule(s):
.invalid {
border-color: rgb(238, 90, 90);
}
validateInput function:
const validateInput = (movieObject) => {
if (movieObject.name.length === 0) {
setValidations((prevState) => {
return { ...prevState, isNameValid: false };
});
} else {
setValidations((prevState) => {
return { ...prevState, isNameValid: true };
});
}
if (movieObject.ratings.length === 0) {
setValidations((prevState) => {
return { ...prevState, isRatingValid: false };
});
} else if (
parseInt(movieObject.ratings) >= 0 &&
parseInt(movieObject.ratings) <= 100
) {
setValidations((prevState) => {
return { ...prevState, isRatingValid: true };
});
}
if (movieObject.duration.length === 0) {
setValidations((prevState) => {
return { ...prevState, isDurationValid: false };
});
} else {
setValidations((prevState) => {
return { ...prevState, isDurationValid: true };
});
}
console.log(validations);
return (
validations.isNameValid &&
validations.isRatingValid &&
validations.isDurationValid
);
};
Based on validations state, className is applied (or not):
<form onSubmit={handleFormSubmit}>
<div className="layout-column mb-15">
<label htmlFor="name" className="mb-3">
Movie Name
</label>
<input
className={`${!validations.isNameValid ? "invalid" : ""}`}
type="text"
id="name"
placeholder="Enter Movie Name"
data-testid="nameInput"
value={newMovie.name}
onChange={handleChangeEvent}
/>
</div>
<div className="layout-column mb-15">
<label htmlFor="ratings" className="mb-3">
Ratings
</label>
<input
className={!validations.isRatingsValid ? "invalid" : ""}
type="number"
id="ratings"
placeholder="Enter Rating on a scale of 1 to 100"
data-testid="ratingsInput"
value={newMovie.ratings}
onChange={handleChangeEvent}
/>
</div>
<div className="layout-column mb-30">
<label htmlFor="duration" className="mb-3">
Duration
</label>
<input
className={!validations.isDurationValid ? "invalid" : ""}
type="text"
id="duration"
placeholder="Enter duration in hours or minutes"
data-testid="durationInput"
value={newMovie.duration}
onChange={handleChangeEvent}
/>
</div>
<div className="layout-row justify-content-end">
<button type="submit" className="mx-0" data-testid="addButton">
Add Movie
</button>
</div>
</form>
Anybody can point out a better way to apply validations? I feel like there is a lot of repetition here and the fact that Ratings has a red border even at the start, how can this be fixed?
I am validating some details, the problem is when the validation is complete and I want to move to the next page with submit. it logs in with the second try
I have tried to put all the validation process to the OnChange function, but it messes up all of the validation process, I have also tried to put the error variables to the state but I receive an error message that It's constant variables and can't be changed.
import { Link } from 'react-router-dom';
class Profile extends Component {
state = {
details: {
firstName: '',
lastName: '',
id: '',
email: ''
},
error: false,
complete: false
};
OnSubmit = e => {
e.preventDefault();
let re = /^(([^<>()\[\]\\.,;:\s#"]+(\.[^<>()\[\]\\.,;:\s#"]+)*)|(".+"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
const { email } = this.state.details;
const { firstName } = this.state.details;
const { lastName } = this.state.details;
const { id } = this.state.details;
let errorid = false;
let errorfirstlast = false;
let erroremail = false;
if (id.length <= 9 && id !== '') {
console.log('trueid');
errorid = false;
} else {
errorid = true;
console.log('falseid');
}
if (re.test(email)) {
console.log('trueemail');
erroremail = false;
} else {
erroremail = true;
console.log('falseemail');
}
if (
firstName !== '' &&
lastName !== '' &&
firstName.substr(0, 1) === firstName.substr(0, 1).toUpperCase() &&
lastName.substr(0, 1) === lastName.substr(0, 1).toUpperCase() &&
!firstName.match(/\d/) &&
!lastName.match(/\d/)
) {
console.log('truefirstlast');
errorfirstlast = false;
} else {
errorfirstlast = true;
console.log('falsefirstlast');
}
if (erroremail === true || errorfirstlast === true || errorid === true) {
this.setState({ error: true });
} else {
this.setState({ error: false });
this.setState({ complete: true });
}
};
OnChange = e => {
e.preventDefault();
this.setState({
details: { ...this.state.details, [e.target.name]: e.target.value }
});
};
render() {
return (
<div>
<div className="container text-center mt-4" style={{ width: '500px' }}>
<form className="px-4 py-3" onSubmit={this.OnSubmit}>
<div className="form-group">
{this.state.error === true ? (
<p className="text-danger">
Some of the details are wrong check the fields above
</p>
) : null}
<label>First Name:</label>
<input
type="text"
className="form-control"
onChange={this.OnChange}
name="firstName"
/>
</div>
<div className="form-group">
<label>Last Name:</label>
<input
type="text"
className="form-control"
onChange={this.OnChange}
name="lastName"
/>
</div>
<div className="form-group">
<label>ID Number:</label>
<input
type="text"
className="form-control"
onChange={this.OnChange}
name="id"
/>
</div>
<div className="form-group">
<label>Email:</label>
<input
type="text"
className="form-control"
onChange={this.OnChange}
name="email"
/>
</div>
{this.state.complete === true ? (
<Link to="/success">
<button type="submit" className="btn btn-secondary mt-3">
Check
</button>
</Link>
) : (
<button type="submit" className="btn btn-secondary mt-3">
Check
</button>
)}
</form>
</div>
</div>
);
}
}
export default Profile;
The problem is that I enter the next page with the second click on the submit button, I want to enter with the first try
The reason that routing to the next page only happens on the second click of the Submit button is because the Link to the next page is only rendered after this.state.complete is true, which only happens after hitting submit for the first time.
In other words, the flow you have currently is:
Fill in form, when done, hit the "Check" button
Hitting the "Check" button triggers the onSubmit function. If the input data is valid, set the state variable complete to true.
Updating state triggers a re-render and now the "Check" button contains the Link to the next page.
Click the "Check" button again, which will click the Link and take the user to the next page.
(Note: perhaps the flow would be more clear if you separated the Link from the submit button)
If you want the user to be taken to the next page on the first click of the "Check" button (if the input data is valid), you can control the routing programmatically inside of the onSubmit function, rather than relying on a Link to be clicked. This can be done by passing the desired route to history.push. In fact, with this method, we can do away with the complete state variable entirely (and the Link in your render method).
For example:
import { withRouter } from "react-router-dom";
class Profile extends Component {
onSubmit = e => {
// ... validation
if (erroremail || errorfirstlast || errorid) {
this.setState({ error: true });
} else {
this.props.history.push("/success");
}
}
}
export default withRouter(Profile);
Note that you'll need to wrap Profile in withRouter in order to access this.props.history.
Also a small code-style note: checking if a boolean is equal to true is redundant, since the value itself is already either true or false (which are the outputs of the === operator anyway).
setState is asynchronous, wrapping it in a function call will make it work for you.
if (erroremail === true || errorfirstlast === true || errorid === true) {
this.setState(() => { error: true });
} else {
this.setState(() => { error: false, complete: true });
}
}
I solved this by moving all of the validation to OnChange function.
e.preventDefault();
let re = /^(([^<>()\[\]\\.,;:\s#"]+(\.[^<>()\[\]\\.,;:\s#"]+)*)|(".+"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
const details = { ...this.state.details, [e.target.name]: e.target.value };
this.setState({
details,
complete:
details.id.length <= 9 &&
details.id !== '' &&
re.test(details.email) &&
details.firstName !== '' &&
details.lastName !== '' &&
details.firstName.substr(0, 1) ===
details.firstName.substr(0, 1).toUpperCase() &&
details.lastName.substr(0, 1) ===
details.lastName.substr(0, 1).toUpperCase() &&
!details.firstName.match(/\d/) &&
!details.lastName.match(/\d/)
});
and only set the error in submit .
I am building a user validation website, I want each input to verify if the string that was entered:
Have uppercase first letter
doesn't contain numbers
doesn't contain "$%^&*()"
I did the first task, but I can't do the last ones.
I have tried !isNaN(firstName) === true and it wont work
import React, { Component } from 'react';
class Profile extends Component {
state = {
details: {
firstName: '',
lastName: '',
ID: '',
Email: ''
},
error: false,
complete: false
};
OnSubmit = e => {
e.preventDefault();
const { firstName } = this.state.details;
if (
firstName.charAt(0) !== firstName.charAt(0).toUpperCase() &&
!isNaN(firstName) === true
) {
this.setState({ error: true });
} else {
this.setState({ complete: true });
}
};
OnChange = e => {
e.preventDefault();
this.setState({
details: { ...this.state.details, [e.target.name]: e.target.value }
});
};
render() {
return (
<div>
<div className="container text-center mt-4" style={{ width: '500px' }}>
<form className="px-4 py-3" onSubmit={this.OnSubmit}>
<div className="form-group">
{this.state.error === true ? (
<p className="text-danger">
Some of the details are wrong check the fields above
</p>
) : null}
<label>First Name:</label>
<input
type="text"
className="form-control"
onChange={this.OnChange}
name="firstName"
/>
</div>
<div className="form-group">
<label>Last Name:</label>
<input
type="text"
className="form-control"
onChange={this.OnChange}
name="lastName"
/>
</div>
<div className="form-group">
<label>ID Number:</label>
<input
type="text"
className="form-control"
onChange={this.OnChange}
name="ID"
/>
</div>
<div className="form-group">
<label>Email:</label>
<input
type="text"
className="form-control"
onChange={this.OnChange}
name="Email"
/>
</div>
<button type="submit" className="btn btn-secondary mt-3">
Check
</button>
</form>
</div>
</div>
);
}
}
export default Profile;
function validateName(name) {
var isValidName = true;
if(/[!##$%^&*(),.?":{}|<>]/g.test(name) || !/^[A-Z]/.test(name) || /\d+/g.test(name)) {
isValidName = false;
}
return isValidName;
}
validateName("David")
You can use regex.
!firstName.match(/\d/)
\d checks for the numbers
First split firstName, then check for Number in that array
OnSubmit = e => {
e.preventDefault();
const { firstName } = this.state.details;
let firstNameArr = firstName.split('');
for(value of firstName.split('')){
if (!isNaN(value) {
this.setState({ error: true });
} else {
this.setState({ complete: true });
}
}
};
This is how I would do it:
const test1 = "%2mfas1k";
const test2 = '123';
const test3 = 'test';
function test(str) {
const match = str.match(/\d+/g);
const isArray = Array.isArray(match);
if(isArray) return match.map(Number);
return false
}
// If test return a result not falsy, contains a number
console.log(test(test1)); // [2, 1]
console.log(test(test2)); // [123]
console.log(test(test3)); // false
Here is a working example, i have split each part into its own checker to make it easier to understand.
let string = "Asdfsdf$32";
let special_characters = ['$','%','^','&','*','(',')'];
let string_array = string.split('');
// Upper case check
if(string[0] === string[0].toUpperCase()) {
console.log("First letter is uppercase")
} else {
console.log("First letter is not uppercase")
}
// No numbers check
if(string.match(/\d/)) {
console.log("Digit Found")
} else {
console.log("No Digit Found")
}
// Special Characters
if(string_array.find(item => special_characters.includes(item))) {
console.log("Special Character Found")
} else {
console.log("No Special Character Found")
}
export function checkDigit(username){
if(username.match(/\d/)) {
console.log("Digit Found")
return true;
}else {
return false;
}
}
let username = this.state.name;
if(checkDigit(username)){
showInfoAlert(NAME_VALIDATION_DIGIT)
return
}
i have 3 update textfields, the value of which is coming from a state called edit_obj, like so:
<input type="text" noValidate name="uname_edit" value={this.state.edit_obj.username} onChange={e => this.editchangeHandler(e)} />
when i click on 'edit' button, editClick function works that sets the value of edit_obj like so:
this.setState({edit_obj: editval})
I am attaching the full code. Please let me know how i can edit the value d the textfield:
import React from 'react';
import {FromErrors1} from './formErrors';
import { SlowBuffer } from 'buffer';
class Form extends React.Component{
constructor(props){
super(props);
this.state={
uname: '',
pass: '',
address:'',
salary:'',
addFormValues:{
username:'',
password:'',
address:''
},
errorfields:{
uname_err:'',
pass_err:'',
address_err:'',
salary_err:'',
valid_user:false,
valid_pass:false,
valid_address:false,
valid_salary:false,
},
delete_data:[],
edit_showui:false,
edit_obj:{},
editval:{},
edit_data:[],
editted_uname:''
}
this.changeHandler= this.changeHandler.bind(this)
this.pushAddStudentData=new Array()
this.submitForm= this.submitForm.bind(this);
//this.editchangeHandler = this.editchangeHandler.bind(this)
//this.editClick = this.editClick.bind(this)
}
editClick =(that,editval) =>{
//alert("du")
//show edit ui:
this.setState({edit_showui:true});
//add values to the inputs of show ui
console.log('editval: ',editval);
//this.setState({edit_obj:editval});
//this.setState({edit_data:this.state.edit_data.push(editval)});
/*this.setState((state)=>({
edit_data:state.edit_data.push(editval)
}))*/
this.state.edit_data=[]
this.setState(prevState => ({
edit_data: [...prevState.edit_data, editval]
}))
this.setState({edit_obj: editval})
console.log("edit_obj:::::::",this.state.edit_obj)
}
editchangeHandler = (e) =>{
console.log('ename::',e.target.name)
console.log('etarget::',e.target.value)
//this.setState({[e.target.name]:e.target.value})
console.log('edit_obj::',this.state.edit_obj)
//newEditVal
//this.state.newEditVal.username =
/*
if(e.target.name=='uname_edit'){
console.log('uname_edit')
//editted_uname
this.setState(
{editted_uname : ''}
)
console.log('editted_uname::',this.state.editted_uname)
}
if(e.target.name=='pass_edit'){
console.log('pass_edit')
}
if(e.target.name=='address_edit'){
console.log('address_edit')
}
*/
//this.setState({})
this.setState({
[e.target.name]: e.target.value
});
}
updateval=()=>{
console.log('EDIT_OBJ: ',this.state.edit_obj)
}
deleteClick =(e,f) =>{
console.log("sefr",e,'a::',f);
// if(this.pushAddStudentData.indexOf(f) > -1){
// }
let finaldeleteddata=[];
for( var i = 0; i < this.state.delete_data.length; i++){
console.log('this.state.delete_data[i]===f:: ',this.state.delete_data[i]===f)
console.log('and f:: ',f)
if ( this.state.delete_data[i] === f) {
this.state.delete_data.splice(i, 1);
// this.setState(
// {
// delete_data:finaldeleteddata
// }
// )
this.setState(prevState => ({
delete_data: [...prevState.delete_data]
}))
}
console.log('YEYEYEYEEDITDATATAa:: ',this.state.delete_data)
console.log("finaldeleteddata:: ",finaldeleteddata)
}
}
changeHandler = (ev) =>{
// alert("gugugu")
this.setState({[ev.target.name]:ev.target.value})
console.log(this.state)
}
submitForm = (e) =>{
let finaladdeddata;
e.preventDefault();
console.log('this.state.uname:',this.state.uname);
console.log('this.state.pass:',this.state.pass);
let usererror = {...this.state.errorfields};
var regex_username = new RegExp(/^[a-zA-Z ]*$/);
if(this.state.uname && regex_username.test(this.state.uname)){
//no error
// this.state.valid_user= true; /THIS IS NOT RIGHT WAY, USE THIS.SETSTATE
alert("iffff");
usererror.uname_err='';
usererror.valid_user = true
console.log("usererror::",usererror)
console.log("this.STATEuserif:::",this.state.errorfields.valid_user)
this.setState({errorfields: usererror});
}else{
//else of user
alert('2user')
console.log('usererror: ',usererror)
usererror.uname_err= 'username not valid';
usererror.valid_user = false;
this.setState({errorfields: usererror});
//there is error
console.log("this.STATEuserelse:::",this.state)
}
if(this.state.pass && this.state.pass.length <=6){
//if of pass
//no error
// this.state.valid_pass= true;
usererror.valid_pass=true;
usererror.pass_err='';
this.setState({errorfields:usererror})
console.log("this.STATEpassif:::",this.state)
}else{
//else of pass
alert('2pass')
usererror.valid_pass=false;
usererror.pass_err='invalid password | password length more than 6';
this.setState({errorfields:usererror})
//there is error
console.log('this.state.errorfields',this.state.errorfields)
console.log("this.STATE2:::",this.state)
}
//usererror
//errorfields
console.log("address:", this.state.address)
console.log("salary:", this.state.salary)
//put error fields in address
if(this.state.address && this.state.address.length<=20){
// this.state.valid_address=true;
usererror.address_err='';
usererror.valid_address=true
this.setState({errorfields:usererror})
} else{
usererror.address_err='Empty address | address length more than 20';
usererror.valid_address=false
this.setState({errorfields:usererror})
}
/*form={}
uname: '',
pass: '',
address:''
}*/
console.log('usererror.valid_address',usererror.valid_address);
console.log('usererror.valid_pass',usererror.valid_pass);
console.log('usererror.valid_user',usererror.valid_user);
if(usererror.valid_address==true && usererror.valid_pass==true && usererror.valid_user==true){
alert("YESSS");
let addFormValues_dupl= {...this.state.addFormValues};
addFormValues_dupl.username = this.state.uname;
addFormValues_dupl.password = this.state.pass;
addFormValues_dupl.address = this.state.address;
console.log('addFormValues_dupl',addFormValues_dupl);
// this.pushAddStudentData.push(addFormValues_dupl)
//this.setState({delete_data:addFormValues_dupl})
this.state.delete_data.push(addFormValues_dupl)
console.log('state',this.state);
// this.setState({addFormValues: this.state.uname})
}else{
alert("NOOO")
//this.pushAddStudentData=[]
console.log('pushAddStudentDataELSE',this.pushAddStudentData[0]);
}
}
render(){
return(
<div>
<h2>Add Employee info</h2>
<div className="displayerrors">
{/* <ul>{this.state.errorfields.map((a,i)=>{<li>a</li>})}</ul> */}
<input type="hidden" value={this.state.errorfields}/>
<p>{this.state.errorfields.uname_err} - {this.state.errorfields.valid_user}</p>
<p>{this.state.errorfields.pass_err}</p>
<p>{this.state.errorfields.address_err}- {this.state.errorfields.valid_address}</p>
</div>
<div>
<label>username:</label>
<input type="text" noValidate name="uname" onChange={this.changeHandler}/>
</div>
<div>
<label>password:</label>
<input type="password" noValidate name="pass" onChange={this.changeHandler}/>
</div>
<div>
<label>address:</label>
<textarea noValidate name="address" onChange={this.changeHandler}></textarea>
</div>
<div>
<button onClick={this.submitForm}></button>
</div>
<div>{this.state.delete_data.length}
{this.state.delete_data.map((a,i)=>{
return <ul key={i}> <li>{i}</li><li>{a.username}</li>
<li>{a.password}</li>
<li>{a.address}</li>
<li><a href="#" onClick={()=>{this.deleteClick(this,a)}}>Delete</a></li>
<li><a href="#" onClick={()=>{this.editClick(this,a)}}>Edit</a></li></ul>
})}
</div>
{ this.state.edit_showui==true &&
<div>
<div>
<label>username:</label>
<input type="text" noValidate name="uname_edit" value={this.state.edit_obj.username} onChange={e => this.editchangeHandler(e)} />
</div>
<div>
<label>password:</label>
<input type="password" noValidate name="pass_edit" value={this.state.edit_obj.password} onChange={this.editchangeHandler.bind(this)} />
</div>
<div>
<label>address:</label>
<textarea noValidate name="address_edit" value={this.state.edit_obj.address} onChange={this.editchangeHandler.bind(this)}></textarea>
</div>
<div>
<button onClick={this.updateval.bind(this)}>update</button>
</div>
<div>{this.state.edit_obj.username}</div>
<div>{this.state.edit_obj.password}</div>
<div>{this.state.edit_obj.address}</div>
</div>
}
editdata:
<div>{this.state.edit_data.username}</div>
<div>{this.state.edit_data.password}</div>
<div>{this.state.edit_data.address}</div>
{this.state.edit_data.map((q,i)=>{
return <ul key={i}> <li>{i}</li><li>{q.username}</li>
<li>{q.password}</li>
<li>{q.address}</li>
</ul>
})}
}
</div>
)//return ends
}
}
export default Form;
thanks in advance.