Skip to content

Login Form with ReactJS

import React, { Component } from 'react';
import { Button, Form, FormGroup, Label, Input, Fade  } from 'reactstrap';
import _ from 'lodash';

const validationMethods =  {
    required : (field, value) => {
        if (!value.toString().trim().length) {
            return  `This ${field} field is required.`
        }
    },
    isEmail: (field,value) => {
        var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
        if (reg.test(value) === false) {
            return  `Invalid Email Address.`
        }        
    }
} 

const validateForm = (form) => {
    const loginForm = document.getElementById(form)
     return loginForm.querySelectorAll('[validations]');
}

const runValidationRules  = (element, errors) => {
    const target = element;
    const field =  target.name;
    const value = target.value
    let validations =  element.getAttribute('validations');
    validations =  validations.split(',')

    for (let validation of validations) {
        validation = validation.split(':');
        const rule = validation[0];
        const error = validationMethods[rule](field, value);
        errors[field] = errors[field] || {};
        if(error) {
            errors[field][rule] = error;
        } else {
            if(_.isEmpty(errors[field])) {
                delete errors[field];
            } else {
                delete errors[field][rule];
            }
        }
    }

    return errors;
}


export default class Login extends Component {

    constructor(props) {
        super(props);
        this.state = {
            email: '',
            password: '',
            errors: []
        }
    }



    login = (event) => {

        event.preventDefault();

        const formElements = validateForm("loginForm");
 
        formElements.forEach(element=> {
           const errors = runValidationRules(element, this.state.errors);
            this.setState({
                errors: errors
            });
        })

        const email = this.state.email;
        const password = this.state.password;
        const errors =  this.state.errors;
        console.log(email, password, errors);
    }

    handleChange = (event) => {
        const target = event.target;
        const field =  target.name;
        const value = target.value

        const errors = runValidationRules(target, this.state.errors);

        this.setState({
            errors: errors
        });

        this.setState({
            [field]:  value
        });
    }

    render() {
        return (
            
); } } const FromValidationError = props => ( { props.field ? Object.values(props.field).shift() : '' } );
0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments