简体   繁体   中英

Regex to not match leading and trailing white spaces for email address in javascript

Currently, I use this email regex:

/^[a-zA-Z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,4}$/

I try to validate the email like below:

 if (!event.target.value.match(/^[a-zA-Z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,4}$/)) {
     setEmailStatus('Enter valid email address');
 }

But when entering with trailing and leading spaces it doesn't throw any error. eg hello@gmail.com

How to validate the spaces for the above regex?

Here is the complete code:

const [ usernamevalues, setUsername ] = React.useState({ username: '' });
const [ emailvalues, setEmail ] = React.useState({ email: '' });
const [ usernameStatus, setUsernameStatus ] = React.useState('');
const [ emailStatus, setEmailStatus ] = React.useState('');

const handleChangeEmail = (prop) => (event) => {
    event.preventDefault();
    if (event.target.value.length === 0) {
        setEmailStatus('This field is required');
    } else if (!event.target.value.match(/^[a-zA-Z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,4}$/)) {
        setEmailStatus('Enter valid email address');
    } else {
        setEmailStatus('');
    }

    /*if (validator.isEmpty(event.target.value)) {
        setEmailStatus('This field is required');
    }*/

    setEmail({ ...emailvalues, [prop]: event.target.value });
};

Based on the errors, I'm trying to enable submit button. I'm maintaining state for the above fields.

let isEnabled = usernamevalues.username !== '' && usernamevalues.username.length >= 1
  && emailvalues.email !== '' && usernameStatus !== 'This field is required' && usernameStatus !== 'Enter valid username'
  && emailStatus !== 'This field is required' && emailStatus !== 'Enter valid email address'

<TextField
        label='Email'
        id='outlined-margin-normal'
        placeholder='Email'
        value={emailvalues.email}
        type='email'
        className={classes.textField}
        margin='normal'
        variant='outlined'
        onChange={handleChangeEmail('email')}
        InputLabelProps={{
            classes: {
                root: classes.cssLabel,
                focused: classes.cssFocused
            }
        }}
        InputProps={{
            endAdornment: (
            <InputAdornment position='end'>
                <EmailOutlinedIcon htmlColor='#1C5FAB' opacity={0.5} />
            </InputAdornment>
        ),
        classes: {
            root: classes.cssOutlinedainput,
            focused: classes.cssFocused,
            notchedOutline: classes.notchedOutline,
            input: classes.input
        }
    }}
    error={emailStatus ? emailStatus : ''}
    helperText={emailStatus !== '' ? emailStatus : null}
/>
<Typography className={classes.error}>{error}</Typography>
<Button
    variant='outlined'
    className={classes.button}
    onClick={handleSubmit}
    disabled={!isEnabled}
    style={{ backgroundColor: isEnabled ? '#1c60ab' : '#DCE2EB'}}
>
    Submit
</Button>

You don't need regex. Use trim() ( docs )

using your example:

if (!event.target.value.trim().match(/^[a-zA-Z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,4}$/)) {
     setEmailStatus('Enter valid email address');
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM