const phoneExp = /\(?![0])|[0])[0-9](?[0-9])?[0-9]*$/;
const formValid = formErrors => { let valid = true; Object.values(formErrors).forEach(val => { val.length > 0 && (valid = false); });
return valid
}
class App extends React.Component { constructor(props) { super(props) this.state={ nameInput: null, phoneInput: null, formErrors:{ nameInput:"", phoneInput:"" } } } handleSubmit = e =>{ e.preventDefault(); if(formValid(this.state.formErrors)){ console.log( --SUBMITTED-- --nameInput:${this.state.nameInput} --phoneInput:${this.state.phoneInput} ); }else{ console.log(error) } }
--SUBMITTED-- --nameInput:${this.state.nameInput} --phoneInput:${this.state.phoneInput}
error
handleChange = e => { e.preventDefault(); const {name, value} = e.taret;console.log(name,value) let formErrors = this.state.formErrors; switch(name){ case 'nameInput': formErrors.nameInput = value.length < 3 && value.length > 0 ? "name too short" : "please enter a name"; break; case 'phoneInput': formErrors.phoneInput = phoneExp.test(value) && value.length > 0 ? "please enter a phone number" : "bad phone number"; break; default: break; } } render() { return ( <> <h1>here we go again</h1> <form onSubmit={this.handleSubmit}> <div className="nameInput"> <label htmlFor="nameInput" noValidate >Name:</label> <input type="text" noValidate name="nameInput" onChange={this.handleChange} /> </div> <div className="phoneInput"> <label htmlFor="phoneInput" noValidate >Phone:</label> <input type="text" noValidate name="phoneInput" onChange={this.handleChange} /> </div> <div className="saveNumbers"> <button type="submit">save</button> </div> </form> </> ) }
document.addEventListener('DOMContentLoaded', function () { ReactDOM.render( , document.getElementById('app') ); });
Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment's permalink.
Hide child comments as well
Confirm
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
const phoneExp = /\(?![0])|[0])[0-9](?[0-9])?[0-9]*$/;
const formValid = formErrors => {
let valid = true;
Object.values(formErrors).forEach(val => {
val.length > 0 && (valid = false);
});
}
class App extends React.Component {
constructor(props) {
super(props)
this.state={
nameInput: null,
phoneInput: null,
formErrors:{
nameInput:"",
phoneInput:""
}
}
}
handleSubmit = e =>{
e.preventDefault();
if(formValid(this.state.formErrors)){
console.log(
);--SUBMITTED--
--nameInput:${this.state.nameInput}
--phoneInput:${this.state.phoneInput}
}else{
console.log(
error
)}
}
}
document.addEventListener('DOMContentLoaded', function () {
ReactDOM.render(
,
document.getElementById('app')
);
});