Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How can I check if field is a valid Email Address OR a valid Username #1020

Closed
nikas-belogolov opened this issue Apr 12, 2021 · 3 comments
Closed

Comments

@nikas-belogolov
Copy link

nikas-belogolov commented Apr 12, 2021

I want to check if a field is a valid email address OR if it's a valid username.

This is how I would do it normally in javascript:

if (value === undefined) return false; // Check if value is undefined. If it is, return false.
if (isEmail(value)) return true; // If value isn't undefined, then check if it's a valid email address.
if (value.match(/^[a-z0-9]+$/i)) return true; // If value isn't an email, then it's got to be a username.
return false; // If value isn't an email address and not a username, then it's an invalid value.

How can I do the same in express-validator?

Note: the field is the same field, "username".

@fedeci
Copy link
Member

fedeci commented Apr 12, 2021

You can use this middleware:

oneOf([
  body('paramName').exists().isEmail(),
  body('paramName').matches(/*your regex*/),
])

@nikas-belogolov
Copy link
Author

nikas-belogolov commented Apr 12, 2021

it doesn't work, it returns these errors with this input:

input: "Hello@#$%"
errors:

[
  { // Error from invalid username or email address
    value: 'Hello@#$%',
    msg: 'Enter a valid username or email address',
    param: 'username',
    location: 'body'
  },
  { // Error from invalid email
    value: 'Hello@#$%',
    msg: 'Invalid value',
    param: 'username',
    location: 'body'
  }
]

but it should only return one error if the text isn't a username or email address

Heres my code:

oneOf([

    body("username").matches(/^[a-z0-9]+$/i).withMessage((value, { req }) => {
        return req.t("validation:field_valid", { field: req.t("account.username_or_email") });
    }),

    body("username")
        .exists().withMessage((value, { req }) => {
            return req.t("validation:field_required", { field: req.t("account.username_or_email") })
        })
        .isEmail()

    
]

@fedeci
Copy link
Member

fedeci commented Apr 12, 2021

Hello@#$% is not an email and does not matches the regex you provided😄


edit: sorry @anonymous675, I misread your answer. That behavior has already been marked in #956 and will probably be changed in v7.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants