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!
needs-validation'?<form>tag.