Skip to content
Advertisement

React email address format validation

I’m building a portal where students from only 6 universities can participate so I need a way to limit the email address type to these 6 universities for example emails ending with @mit.edu

enter image description here

How do I implement this in React with the form validation set to characters and on clicking on of these formats from the dropdown the email is saved as such for example in the email input field if you write cassandra and select @mit.edu from the dropdown the email becomes cassandra@mit.edu

This is how my login component looks like `

function LogIn() {

    const [password, setPassword] = React.useState("");
    const [email, setEmail] = React.useState("");
    const [err, setErr] = React.useState(null);

    const history = useHistory();

    const handleSubmit = async (event, password, email) => {
        event.preventDefault();

        var myHeaders = new Headers();
        myHeaders.set('Authorization', 'Basic ' + encode(email + ":" + password));

        var requestOptions = {
        method: 'GET',
        headers: myHeaders,
        redirect: 'follow'
        };

        let response;

        try {
            response = await fetch (`${APIlink}/users`, requestOptions)
        } catch (err) {
            setErr("Incorrect Password. Please Retry.");
            return;
        }

        const result = await response.text();
        //console.log(result);
        const json = JSON.parse(result);
        //console.log(json);
        //console.log(response);
        

        if (response.status===200) {
            setErr(null);
            localStorage.setItem('isAuthenticated', true);
            //context.updateToken(JSON.stringify(json.data));
            history.push("/Projects");
            } else {
            setErr(json.error);
            console.log(json.error);
            }
        };

        return (
            <div>
                <Header />
            <div className="register row justify-content-center align-items-center">

             <div className = "w-50 p-3">
                <h1>Log in</h1>
                <Link to="/Register">or create a new account</Link>
                <br></br>
                <br></br>
                <form>
                <div className="input-group mb-3">
                <input type="text" id="email"   
                value={email}
                onChange= {(event) => {
                    setErr("");
                    setEmail(event.target.value); }}
                className="form-control form-control-lg" placeholder=" institute email" aria-label="institute-email" aria-describedby="basic-addon2"/>
                </div>

                <small
                style={{ color: "red", height: "10px", display: "inline-block" }}
                >
                {err == "user not found" ? "Account doesn't exist" : ""}
                </small>


                <div className="input-group mb-3">
                <input type="text" id="password"
                value={password}
                onChange={(event) => {
                    setPassword(event.target.value);
                    setErr("");
                }}
                className="form-control form-control-lg" placeholder="password" aria-label="password" aria-describedby="basic-addon2"/>
                </div>

                <small
                style={{ color: "red", height: "10px", display: "inline-block" }}
                >
                {err == "incorrect password"
                    ? "Incorrect Password"
                    : err == "Username and Password can't be empty"
                    ? err
                    : ""}
                </small>

               

                
                <Submit
                //loginState={loginState}
                onClick={(event) => {
                  event.preventDefault();
                  if (email != "" && password != "") {
                    handleSubmit(event, password, email);
                  } else {
                    setErr("Username and Password can't be empty");
                  }
                }}
              >
                {" "}
                Log In
              </Submit>
               
                </form>
                </div>
                
                
                

            </div>
            </div>
        )
    }


export default LogIn;

`

Advertisement

Answer

You can use regex to validate email. Add this validateEmail function right after clicking on submit and pass the email that you want to validate, then proceed further only if it returns true (it will return true if it matches the pattern).

function validateEmail(email) 
    {
        var regex = /^[^s@]+@mit.edu$/;
        var result = regex.test(email);
        if(result == true){
            //Proceed further
        }
        else{
            console.log("Enter correct email address!")
        }
    }

According to this regex, it will return true only if there is exact ‘@mit.edu’ right after any string. Like:-

‘anystring@mit.edu’ //Returns true

‘anystring@mit.com’ //Returns false

‘anystring@mit.edu.com’ //Returns false

You can do this similarly with other domains just replace mit.edu with any other domain or if the domain has more length then simply add '.domain' for example: –

var regex = /^[^s@]+@mit.edu.com$/;

This will return true if email is ‘anystring@mit.edu.com’.

EDIT: A slight correction. Remove ‘+’ after mit and edu, as it returns true on these conditions: –

anystring@mitt.edu

anystring@mit.eduu

Check the regex above now, it should work perfectly.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement