Search
 
SCRIPT & CODE EXAMPLE
 

JAVASCRIPT

react form validation

const {
  handleSubmit, // handles form submission
  handleChange, // handles input changes
  data, // access to the form data
  errors, // includes the errors to show
} = useForm({ // the hook we are going to create
  validations: { // all our validation rules go here
    name: {
      pattern: {
        value: '^[A-Za-z]*$',
        message:
          "You're not allowed ...",
      },
    },
  },
  onSubmit: () => alert('User submitted!'),
  initialValues: { // used to initialize the data
    name: 'John',
  },
});

// ...
return (
  <form onSubmit={handleSubmit}>
    <input value={data.name || ''} onChange={handleChange('name')} required />
    {errors.name && <p className="error">{errors.name}</p>}
    {/** ... */}
  </form>
);
Comment

react form validation

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 (
      <div>
        <form
          name="contactform"
          className="contactform"
          onSubmit={this.contactSubmit.bind(this)}
        >
          <div className="col-md-6">
            <fieldset>
              <input
                ref="name"
                type="text"
                size="30"
                placeholder="Name"
                onChange={this.handleChange.bind(this, "name")}
                value={this.state.fields["name"]}
              />
              <span style={{ color: "red" }}>{this.state.errors["name"]}</span>
              <br />
              <input
                refs="email"
                type="text"
                size="30"
                placeholder="Email"
                onChange={this.handleChange.bind(this, "email")}
                value={this.state.fields["email"]}
              />
              <span style={{ color: "red" }}>{this.state.errors["email"]}</span>
              <br />
              <input
                refs="phone"
                type="text"
                size="30"
                placeholder="Phone"
                onChange={this.handleChange.bind(this, "phone")}
                value={this.state.fields["phone"]}
              />
              <br />
              <input
                refs="address"
                type="text"
                size="30"
                placeholder="Address"
                onChange={this.handleChange.bind(this, "address")}
                value={this.state.fields["address"]}
              />
              <br />
            </fieldset>
          </div>
        </form>
      </div>
    );
  }
}

React.render(<Test />, document.getElementById("container"));
Comment

react form validation

import { useForm } from "react-hook-form";
Comment

PREVIOUS NEXT
Code Example
Javascript :: jest always pass async await 
Javascript :: angular $http abort request 
Javascript :: javascript call stacks 
Javascript :: how to redirect to another page without writing javascript 
Javascript :: set state using object 
Javascript :: fibonacci recursive method 
Javascript :: Find Dubplicate In Array of Object 
Javascript :: change height of div with scroll in javascript 
Javascript :: comparison operators in javascript 
Javascript :: merge two sorted linked lists 
Javascript :: olx clone react 
Javascript :: routerlink not working 
Javascript :: sequelize 
Javascript :: await javascript 
Javascript :: check if the collection exists in mongodb database mongoose 
Javascript :: javascript Symbol Methods 
Javascript :: convert js to python online 
Javascript :: list in react native 
Javascript :: what are escape characters in javascript 
Javascript :: vue radio checked if 
Javascript :: hide component vuejs 
Javascript :: string javascript concatenation 
Javascript :: scirpt tag react 
Javascript :: how to check if it is the current time day.js 
Javascript :: javascript object methods 
Javascript :: stringy 
Javascript :: vue js override component css 
Javascript :: console.log() Syntax 
Javascript :: js rename property 
Javascript :: _.pluck 
ADD CONTENT
Topic
Content
Source link
Name
3+8 =