How to Validate an Email address in React using functional components?

此生再无相见时 提交于 2021-02-11 15:16:22

问题


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

回答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);
}


来源:https://stackoverflow.com/questions/61314849/how-to-validate-an-email-address-in-react-using-functional-components

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!