Skip to content

Instantly share code, notes, and snippets.

@iraniamir
Created October 28, 2018 16:08
Show Gist options
  • Save iraniamir/10a6968b05038b9d34a83d490790e72f to your computer and use it in GitHub Desktop.
Save iraniamir/10a6968b05038b9d34a83d490790e72f to your computer and use it in GitHub Desktop.
React html5 form validation
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { EMLINK } from 'constants';
export default class FormValidation extends Component {
static propTypes = {
children: PropTypes.node,
submit: PropTypes.func.isRequired
};
state = {
isValidated: false
}
validate = () => {
const formLength = this.formEl.length;
for (let i = 0; i < formLength; i++) {
const elem = this.formEl[i];
const errorLabel = elem.parentNode.parentNode.querySelector('.invalid-feedback');
if (errorLabel) {
elem.classList.remove('bp3-intent-warning');
errorLabel.remove();
}
};
if (Object.is(this.formEl.checkValidity(), false)) {
for (let i = 0; i < formLength; i++) {
const elem = this.formEl[i];
const parentElem = elem.parentNode.parentNode;
if (!elem.validity.valid) {
let newLabel = document.createElement('div');
newLabel.className = 'invalid-feedback bp3-form-helper-text';
if (elem.validity.valueMissing) {
newLabel.textContent = "پر کردن این فیلد الزامیست !";
} else if (elem.validity.tooLong) {
newLabel.textContent = "تعداد کارکترهای این فیلد طولانی است !";
} else if (elem.validity.tooShort) {
newLabel.textContent = "تعداد کارکترهای این فیلد کوتاه است !";
} else {
newLabel.textContent = elem.validationMessage;
}
parentElem.appendChild(newLabel);
elem.classList.add('bp3-intent-warning');
}
}
return false;
}
return true;
}
submitHandler = (event) => {
event.preventDefault();
if (this.validate()) {
this.props.submit();
}
this.setState({ isValidated: true });
}
render() {
let classNames = [];
if (this.state.isValidated) {
classNames.push('was-validated');
}
return (
<form ref={form => this.formEl = form} onSubmit={this.submitHandler} className={classNames} noValidate>
{this.props.children}
</form>
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment