Config Router

  • Google Sheets
  • CCNA Online training
    • CCNA
  • CISCO Lab Guides
    • CCNA Security Lab Manual With Solutions
    • CCNP Route Lab Manual with Solutions
    • CCNP Switch Lab Manual with Solutions
  • Juniper
  • Linux
  • DevOps Tutorials
  • Python Array
You are here: Home / Reactjs – Form input validation

Reactjs – Form input validation

August 16, 2021 by James Palmer

You should avoid using refs, you can do it with onChange function.
On every change, update the state for the changed field.
Then you can easily check if that field is empty or whatever else you want.
You could do something as follows :
class Test extends React.Component {
constructor(props) {
super(props);

this.state = {
fields: {},
errors: {},
};
}

handleValidation() {
let fields = this.state.fields;
let errors = {};
let formIsValid = true;

//Name
if (!fields[“name”]) {
formIsValid = false;
errors[“name”] = “Cannot be empty”;
}

if (typeof fields[“name”] !== “undefined”) {
if (!fields[“name”].match(/^[a-zA-Z]+$/)) {
formIsValid = false;
errors[“name”] = “Only letters”;
}
}

//Email
if (!fields[“email”]) {
formIsValid = false;
errors[“email”] = “Cannot be empty”;
}

if (typeof fields[“email”] !== “undefined”) {
let lastAtPos = fields[“email”].lastIndexOf(“@”);
let lastDotPos = fields[“email”].lastIndexOf(“.”);

if (
!(
lastAtPos < lastDotPos && lastAtPos > 0 &&
fields[“email”].indexOf(“@@”) == -1 &&
lastDotPos > 2 &&
fields[“email”].length – lastDotPos > 2
)
) {
formIsValid = false;
errors[“email”] = “Email is not valid”;
}
}

this.setState({ errors: errors });
return formIsValid;
}

contactSubmit(e) {
e.preventDefault();

if (this.handleValidation()) {
alert(“Form submitted”);
} else {
alert(“Form has errors.”);
}
}

handleChange(field, e) {
let fields = this.state.fields;
fields[field] = e.target.value;
this.setState({ fields });
}

render() {
return (


{this.state.errors[“name”]}


{this.state.errors[“email”]}





);
}
}

React.render(, document.getElementById(“container”));

In this example I did the validation only for email and name, but you have an idea how to do it. For the rest you can do it self.
There is maybe a better way, but you will get the idea.
Here is fiddle.
Hope this helps.

I’ve taken your code and adapted it with library react-form-with-constraints: https://codepen.io/tkrotoff/pen/LLraZp
const {
FormWithConstraints,
FieldFeedbacks,
FieldFeedback
} = ReactFormWithConstraints;

class Form extends React.Component {
handleChange = e => {
this.form.validateFields(e.target);
}

contactSubmit = e => {
e.preventDefault();

this.form.validateFields();

if (!this.form.isValid()) {
console.log(‘form is invalid: do not submit’);
} else {
console.log(‘form is valid: submit’);
}
}

render() {
return (
this.form = form}
onSubmit={this.contactSubmit}
noValidate>