I want to apply some conditions to the email address of the form field. The email address field is optional. The condition is-
- Do not show any errors when the email field is empty.
- But the error will only show when there is a value in the email field + the mail format does not match.
I did it well with the following jQuery code. But here’s the problem – when I apply this condition [ !$("#billing_email").val().match(/^b[A-Z0-9._%-]+@[A-Z0-9.-]+.[A-Z]{2,4}b$/i ) ], even if the email field is empty, the mail address is still required! But the mail field is not required.
How do I solve this problem?
$('form.checkout').on('submit', function () {
if ( $("#billing_email").val()!== '' && !$("#billing_email").val().match(/^b[A-Z0-9._%-]+@[A-Z0-9.-]+.[A-Z]{2,4}b$/i )) {
if ( $("#billing_email").parent().next(".error").val() !== '') {
$("#billing_email").parent().after("<span class='error'>Invalid email...</span>");
$("#billing_email").focus(); //Focus on field
}
}
else {
$("#billing_email").parent().next(".error").remove();
}
});
3
Answers
Your code is just works fine. I think you might need to add:
before the
if
condition.I assume that there’s no problem with the front-end code. You are using woocommerce right? and you need the
billing email address
as optional. You need to set thebilling email
not required usingwoocommerce_checkout_fields
hook infunctions.php
The code is working as intended. I just tweaked it a bit to be more readable and to have more ‘ specific ‘ conditions.
Check below
( i changed from submit to click so i can test it without submitting, you can change it back to submit )