0

I am working on a React project in that project I have a form, In that form I am trying to do

Validation for an email address, but I don't know how to apply all these.

What I am expecting is, In input tag if I type mark, then If I go to another Input tag it has to

Show me some kind of message above Input tag like this, please enter a valid email address.

This is Form.js

import React from 'react';
import './Form.css';

const Form = () => {

    const validation = (email) => {
        const result = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
    return result.test(String(email).toLowerCase());
    }


    return (
        <div className='container'>
            <div className='row'>
                <div className='col-4'>
                    <div className='mainForm'>
                        <form>
                            <div className="form-group">
                                <label htmlFor="exampleInputEmail1">Email address</label>
                                <input type="email" className="form-control" id="exampleInputEmail1" aria-describedby="emailHelp" />
                            </div>
                            <div className="form-group">
                                <label htmlFor="exampleInputPassword1">Password</label>
                                <input type="password" className="form-control" id="exampleInputPassword1" />
                            </div>
                            <button type="submit" className="btn btn-primary">Submit</button>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    )
}

export default Form
Vamsi
  • 372
  • 6
  • 18

1 Answers1

1

I think those are basic problem in all JS code base, you need to catch the input event, using onChange, onBlur, On...etc and bind those event to your react class, like

return <input type=”email” name=”email” value={this.state.email} 
    onChange={this.handleChange.bind(this)}/>

then on the handleChange you can call the email validation

handleChange(event){
   var email = event.target.value;
   // do what ever you want
   validation(email);
}
Khairu Aqsara
  • 1,321
  • 3
  • 14
  • 27
  • Hi @Khairu Aqsara I tried your code why it is showing any error If I type mark on Input tag – Vamsi Apr 20 '20 at 04:11
  • that because the input using onChange event, if you want to Fires the moment that the element loses focus, you need to use onBlur event., you can see this https://www.w3schools.com/tags/ref_eventattributes.asp and https://stackoverflow.com/questions/24873485/using-onblur-with-jsx-and-react – Khairu Aqsara Apr 20 '20 at 04:20