2

I'm desperate. Trying to validate an email-form-field with pattern and it don't work.

This is the field:

<form id="benutzerform" name="benutzerform" action="" method="POST" class="row g-3 mb-3 pb-3 needs-validation" novalidate="true">
....
<div class="input-group has-validation">
    <span class="input-group-text"><i class="bi bi-at"></i></span>
    <input type="email" class="form-control" id="email" pattern="/[^@]+@[^@]+\.[a-zA-Z]{2,}/i" required>
    <div class="invalid-feedback"> Eine korrekte Emailadresse ist unbedingt erforderlich!  </div>
</div>

It always shows the invalid-feedback.

When in console I do this, it works.

mailpattern=/^([\w\.\-]+)@([\w\-]+)((\.(\w){2,4})+)$/i;
mailpattern.test('[email protected]');
true

but validating it with this function fails:

function validateFormFields()
{
    let f = document.getElementsByClassName('needs-validation')[0];
    if (f.checkValidity() === false) 
    {
        f.classList.add('was-validated');
        return false;
    }
    return true;
}

Where am I going wrong?

S O L U T I O N

Both ways (@Developer and @Ryszard Czech) lead to validating the form. But the easiest and fastest way is to remove the slashes. Then checkValidity() works like it should!

5
  • What your elements have this class: needs-validation'? Commented Apr 9, 2021 at 16:56
  • this is the way, bootstrap shows messages at client-side validation. f.checkValidity() adds pseudo-class :invalid or :valid to the formfields and bootstrap shows the invalid-feedback field when form-class is changed to .was-validated Commented Apr 9, 2021 at 16:59
  • Please show your <form> tag. Commented Apr 9, 2021 at 17:12
  • I added the form-tag to my initial post. The rest of the form validates like you would expecrt ... Commented Apr 9, 2021 at 20:55
  • The best way to validate an email address is to send an email and check the return value. Please, have a look at these sites: TLD list; valid/invalid addresses; regex for RFC822 email address Commented Apr 10, 2021 at 9:32

2 Answers 2

2

Use

pattern="[^@]+@[^@]+\.[a-zA-Z]{2,}"

Remove slashes and flag, [a-zA-Z] is case insensitive by itself.

If you need to use the second expression use

pattern="[\w.-]+@[\w.-]+\.\w{2,4}"
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you. Removing the slashes made it work!
1

Is this what you needed? The main 2 problems were that

  1. you didn't have any element with the class with "needs validation" on it, (I added to your function to check if there are no "needs-validation" classes), in order to prevent errors.
  2. the regex you posted was not applied to the code, and the Html f.checkValididy() function didn't seem to be working, so I replaced the Html validation with your regex.

Here's the Snippet:

<html>

<head>

</head>

<body>
    <div class="input-group has-validation">
        <span class="input-group-text"><i class="bi bi-at"></i></span>
        <input type="email" class="form-control needs-validation" id="email" pattern="/[^@]+@[^@]+\.[a-zA-Z]{2,}/i" required>
        <div class="invalid-feedback"> Eine korrekte Emailadresse ist unbedingt erforderlich! </div>
        <button onclick="alert(validateFormFields());">validate!</button>
    </div>
</body>
<script>
    function validateFormFields() {
        if (document.getElementsByClassName('needs-validation').length > 0) {
            let f = document.getElementsByClassName('needs-validation')[0];
            if (emailAdressIsValid(f.value) === false) {
                f.classList.add('was-validated');
                f.classList.remove('needs-validation');
                return false;
            }
        }
        return true;
    }

    function emailAdressIsValid(email) {
        mailpattern = /^([\w\.\-]+)@([\w\-]+)((\.(\w){2,4})+)$/i;
        return mailpattern.test(email);
    }
</script>

</html>

2 Comments

OP uses Bootstrap.
I thought about this solution too. But from the docs I would expect a regex that validates fine in a regex-checker or like described above in the console, should validate in my function too. But it doesn't ...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.