Form Validation Problem (WordPress custom form) – Email submits even if required field is empty

this is my first time here. Hoping one of you brilliant coders can help! I have a client who has a WordPress site that has a custom theme and custom fields and custom registration form. The registration form has added fields, and once submitted, is set up to send the Admin an email notification, as well as the user gets a notice. Those emails are setup as custom fields from ACF.

The issue we are having is that even if the form fields have “required” added, somehow we are getting registrations where two of the fields are blank. I have tried my best to figure out how to fix this with validation (I’m not a programmer, but I can see what’s already been coded, and try to replicate things). Obviously I am not getting it right LOL

Here are the pieces:

In the theme, we have this file:

page-authorize Page Template (tpl-autorize.php)

Code:

<?php
/*
* Template Name: page-authorize
*/

get_header(); ?>
<?php get_template_part('template-part/register-form'); ?>
<?php get_footer(); ?>

So this means it uses the content from “template-part/register-form” I assume.

Next we have that page:

register-form.php (template-part/register-form.php)

Code:

<?php

$user_reg_data = $_POST['traveller'] ?? array();
$agent = $_POST['agent_prismic_id'] ?? '';
$recaptcha = $_POST['g-recaptcha-response'] ?? '';

if(!empty($user_reg_data)) {
    include($_SERVER['DOCUMENT_ROOT'] . '/wp-content/themes/kvi/include/registration.php');
}

if( isset($_POST['wp-submit']) && $_POST['wp-submit'] == 'Log In' ) {

    $recaptcha = $_POST['g-recaptcha-response'] ?? '';
    $reg_errors = new WP_Error;

    if( !recaptcha_validate( $recaptcha ) ) {
        $reg_errors->add('field', 'Error, please enter the captcha again');
    }

    if ( !empty($reg_errors->errors)) {
        $error_string = $reg_errors->get_error_message();
    }

}

$args = [
    'post_type' => 'travel_agent',
    'posts_per_page' => -1,
    'order' => 'ASC',
    'orderby' => 'title'
];

$kvi_agents_query = new WP_Query($args);
$kvi_agents = $kvi_agents_query->posts ?? '';

$reg_login = isset($_GET['register']) ? 'block-reg' : 'block-in';

?>

<script src="https://www.google.com/recaptcha/api.js" async defer></script>

<script>
jQuery(document).ready(function ($) {
        jQuery( '#form-registration .disspace' ).keydown(function(e) {     
            if (event.key === ' ') {
                return false;
            }       
        });
 });
</script>

<div class="container <?=$reg_login?>">

  <?php if( isset($_GET['register']) && isset($_POST['traveller'])) { ?>
  <?php if ( !empty($error_string) ) { ?>
  <div id="message" class="error">
    <p><?=$error_string?></p>
  </div>
  <?php } else { ?>
  <?php
            unset($_POST);
            ?>
  <div class="login-notice-success">
    Successful registration!<br>
    Please, wait for your account to be moderated.
  </div>
  <?php } ?>
  <?php } ?>

  <?php

    if(isset($_GET['checkemail']) && $_GET['checkemail'] == 'confirm') {
        ?>
  <div class="login-notice-success">
    Please, check your email.<br>Password reset instructions have been sent.
  </div>
  <?php
    }

    ?>

  <div class="authorize-block ">
    <div class="authorize-block-item authorize-block-in">Login</div>
    <div class="authorize-block-item authorize-block-reg">Registration</div>
  </div>

  <div class="form-authorizace">

    <?php the_tiny_login_form(); ?>

  </div>

  <form id="form-registration" method="POST" action="/authorize/?register">
    <div class="row">
      <div class="col-md-6">
        <fieldset>
          <legend>Account Info</legend>
          <div class="form-group">
            <label for="traveller_first_name">First name</label>
            <input class="form-control disspace" placeholder="First Name" type="text" name="traveller[first_name]"
              id="traveller_first_name" value="<?=$_POST['traveller']['first_name'] ?? ''?>" required>
          </div>
          <div class="form-group">
            <label for="traveller_last_name">Last name</label>
            <input class="form-control disspace" placeholder="Last Name" type="text" name="traveller[last_name]"
              id="traveller_last_name" value="<?=$_POST['traveller']['last_name'] ?? ''?>" required>
          </div>
          <div class="form-group">
            <label for="traveller_email">Email</label>
            <input class="form-control disspace" placeholder="Email" type="text" name="traveller[email]" id="traveller_email"
              value="<?=$_POST['traveller']['email'] ?? ''?>" required>
            <div class="error-notice traveller_email-error-notice">Email must contain the @ symbol</div>
          </div>
          <div class="form-group">
            <label for="traveller_email">Email Confirmation</label>
            <input class="form-control disspace" placeholder="Confirm Email" type="text" name="traveller[email_confirmation]"
              id="traveller_email_confirmation" value="<?=$_POST['traveller']['email_confirmation'] ?? ''?>" required>
            <div class="error-notice traveller_email_confirmation-error-notice">Email addresses do not match</div>
          </div>
          <div class="form-group">
            <label for="traveller_password">Password</label>
            <input class="form-control disspace" placeholder="Password" type="password" name="traveller[password]"
              id="traveller_password" required>
            <div class="error-notice traveller_password-error-notice">Password must be at least 6 characters</div>
          </div>
          <div class="form-group">
            <label for="traveller_password_confirmation">Password Confirmation</label>
            <input class="form-control disspace" placeholder="Confirm Password" type="password"
              name="traveller[password_confirmation]" id="traveller_password_confirmation" required>
            <div class="error-notice traveller_password_confirmation-error-notice">Password mismatch</div>
          </div>
        </fieldset>
      </div>
      <div class="col-md-6">
        <fieldset>
          <legend>Personal Info</legend>
          <div class="form-group">
            <label for="traveller_phone disspace">Phone</label>
            <input class="form-control disspace" placeholder="Phone" type="text" name="traveller[phone]" id="traveller_phone"
              value="<?=$_POST['traveller']['phone'] ?? ''?>" required>
            <div class="error-notice traveller_phone-error-notice">The phone number contains prohibited characters</div>
          </div>
          <div class="form-group">
            <label for="traveller_state">State / Province</label>
            <input class="form-control disspace" placeholder="State/Province" type="text" name="traveller[state]"
              id="traveller_state" value="<?=$_POST['traveller']['state'] ?? ''?>" required>
          </div>
          <div class="form-group">
            <label for="traveller_country">Country</label>
            <input class="form-control disspace" placeholder="Country" type="text" name="traveller[country]"
              id="traveller_country" value="<?=$_POST['traveller']['country'] ?? ''?>" required>
          </div>
          <div class="form-group">
            <label for="traveller_airline">Airline</label>
            <input class="form-control disspace" placeholder="Airline" type="text" name="traveller[airline]"
              id="traveller_airline" value="<?=$_POST['traveller']['airline'] ?? ''?>" required>
              <div style="color:red; font-weight:bold; margin-top:-10px">* Your request will be denied if you leave this field blank</div>
          </div><br><br>
          <div class="form-group">
            <label for="traveller_employee_number">Employee number</label>
            <input class="form-control disspace" type="text"
              name="traveller[employee_number]" id="traveller_employee_number"
              value="<?=$_POST['traveller']['employee_number'] ?? ''?>" required>
              <div style="color:red; font-weight:bold; margin-top:-10px">* Your request will be denied if you leave this field blank</div>
          </div><br><br>
          <div class="form-group">
            <label for="email">KVI Agent</label>

            <select name="agent_prismic_id" class="form-control" required>
              <option value="" disabled selected>Please Select</option>
              <option value="0">New To KVI – No Agent</option>
              <?php

                            foreach($kvi_agents as $kvi_agent) {
                                $selected = '';

                                if( isset( $_POST['agent_prismic_id'] ) && trim($_POST['agent_prismic_id']) == trim(ucwords(strtolower($kvi_agent->post_title))) ) {
                                    $selected = 'selected';
                                }

                                ?>
              <option value="<?=ucwords(strtolower($kvi_agent->post_title))?>" <?=$selected?>>
                <?=ucwords(strtolower($kvi_agent->post_title))?></option>
              <?php
                            }
                            ?>
            </select>

          </div>
          <div class="form-group">
            <label for="questions" class="label-questions">Questions/Comments?</label>
            <textarea name="questions" row="5" class="form-control"><?=$_POST['questions'] ?? ''?></textarea>
          </div>
          <div class="form-group">
            <div class="checkbox">
              <label class="label-subscribed">
                <input type="checkbox" name="subscribed" id="traveller_subscribed"> I would like to receive email
                updates from KVI Travel
              </label>
            </div>
          </div>

          <div class="form-group">
            <div class="g-recaptcha" data-sitekey="6Le6zz0eAAAAAPP4sGl044nfbEa7JR0gjKVLLhp8"></div>
          </div>
          <input type="submit" class="btn btn-reverse" value="Register">
        </fieldset>
      </div>
    </div>
  </form>

</div>

<script>
window.addEventListener('load', function() {
  const inputL = document.querySelector('input#user');
  if (inputL) {
    inputL.placeholder = 'EMAIL';
  }

  const inputR = document.querySelector('input#pass');
  if (inputR) {
    inputR.placeholder = 'PASSWORD';
  }


});

jQuery(function($) {

  $('.authorize-block-item').click(function() {
    if ($(this).hasClass('authorize-block-reg')) {
      $('.form-authorizace').hide();
      $('#form-registration').fadeIn();
      $('.container').addClass('block-reg');
      $('.container').removeClass('block-in');

    } else if ($(this).hasClass('authorize-block-in')) {
      $('#form-registration').hide();
      $('.form-authorizace').fadeIn();
      $('.container').addClass('block-in');
      $('.container').removeClass('block-reg');
    }
  })

  $('#traveller_password').blur(function() {
    let firstPassword = $(this).val();
    if (firstPassword.length < 6) {
      $(this).addClass('input-form-alert');
      $('.traveller_password-error-notice').fadeIn();
    } else {
      $(this).removeClass('input-form-alert');
      $('.traveller_password-error-notice').fadeOut();
    }
  })

  $("input#traveller_password_confirmation").blur(function() {
    let password = $('#traveller_password').val();
    let passwordConfirm = $(this).val();
    if (password !== passwordConfirm) {
      $(this).addClass('input-form-alert');
      $('.traveller_password_confirmation-error-notice').fadeIn();
    } else {
      $(this).removeClass('input-form-alert');
      $('.traveller_password_confirmation-error-notice').fadeOut();
    }
  });

  $('#traveller_email').blur(function() {
    let userEmail = $(this).val();
    var pos = userEmail.indexOf('@');
    if (-1 !== pos) {
      $(this).removeClass('input-form-alert');
      $('.traveller_email-error-notice').fadeOut();
    } else {
      $(this).addClass('input-form-alert');
      $('.traveller_email-error-notice').fadeIn();
    }

    let emailConfirm = $('#traveller_email_confirmation').val();
    if (emailConfirm.length > 0) {
      if (userEmail !== emailConfirm) {
        $('#traveller_email_confirmation').addClass('input-form-alert');
        $('.traveller_email_confirmation-error-notice').fadeIn();
      } else {
        $('#traveller_email_confirmation').removeClass('input-form-alert');
        $('.traveller_email_confirmation-error-notice').fadeOut();
      }
    }
  })

  $('#traveller_email_confirmation').blur(function() {
    let userEmailConfirm = $(this).val();
    let userEmail = $('#traveller_email').val();
    if (userEmail !== userEmailConfirm) {
      $(this).addClass('input-form-alert');
      $('.traveller_email_confirmation-error-notice').fadeIn();
    } else {
      $(this).removeClass('input-form-alert');
      $('.traveller_email_confirmation-error-notice').fadeOut();
    }
  })

  $('#traveller_phone').blur(function() {
    if (!$(this).val().search(/^(?=.*[0-9])[- +()0-9]+$/)) {
      $(this).removeClass('input-form-alert');
      $('.traveller_phone-error-notice').fadeOut();
    } else {
      $(this).addClass('input-form-alert');
      $('.traveller_phone-error-notice').fadeIn();
    }
  })

})
</script>

<style>
.block-in #form-registration {
  display: none;
}

.block-in .form-authorizace {
  display: block;
}

.block-in .form-authorizace>p {
  text-align: center;
}

.block-reg #form-registration {
  display: block;
}

.block-reg .form-authorizace {
  display: none;
}

.block-in .authorize-block-in {
  text-decoration: underline;
}

.block-reg .authorize-block-reg {
  text-decoration: underline;
}

/*input::-webkit-input-placeholder {
      color: #888 !important;
    }*/

#authorize-form .login-username input::placeholder,
#authorize-form .login-password input::placeholder {
  color: #fff;
}

#authorize-form .login-username input::-webkit-input-placeholder,
#authorize-form .login-password input::-webkit-input-placeholder {
  color: #fff;
}

#authorize-form .login-username input:focus::-webkit-input-placeholder,
#authorize-form .login-password input:focus::-webkit-input-placeholder {
  color: #fff;
}

.authorize-block {
  width: 100%;
  display: flex;
  justify-content: center;
  margin: 55px 0;

}

.authorize-block-item {
  margin: 10px;
  cursor: pointer;
}

.authorize-block-item:hover {
  text-decoration: underline;
  transition: all 05s;
}

.authorize-block-reg {}

.authorize-block-in {}

.form-authorizace form {
  max-width: 330px;
  margin: 0 auto;
}

.form-authorizace form input[type="submit"] {
  font-family: 'GothamPro';
  font-size: 14px;
  text-transform: uppercase;
  color: #2488C2;
  letter-spacing: 1.1px;
  padding: 15px 45px 13px 45px;
  position: relative;
  display: inline-block;
  margin: 15px 0;
  text-decoration: none;
  background: transparent;
  border: 1px solid #2488C2;
  -webkit-transition: all 0.3s ease;
  -khtml-transition: all 0.3s ease;
  -moz-transition: all 0.3s ease;
  -ms-transition: all 0.3s ease;
  -o-transition: all 0.3s ease;
  transition: all 0.3s ease;
}

.form-authorizace form input[type="submit"]:hover {
  background: rgba(0, 0, 0, 0.1);
}

.login-notice {
  display: inline-block;
  text-align: center;
  margin: 0 auto;
  width: 100%;
  font-size: 16px;
  color: #ff1212;
  text-decoration: underline;
}

.login-notice-success {
  display: inline-block;
  text-align: center;
  margin: 0 auto;
  width: 100%;
  font-size: 22;
  color: #07c507;
}

#form-registration .form-group label.label-subscribed:after {
  content: '';
}

.error {
  color: red;
}

#message.error {
  position: absolute;
  margin-left: 0;
  margin-right: 0;
  text-align: center;
  width: 100%;
}
</style>

Then we have this template:

registration.php (include/registration.php)

Code:

<?php

require_once( $_SERVER['DOCUMENT_ROOT'] . '/wp-config.php');

if ( !defined('ABSPATH') ) {
    exit();
}

$reg_errors = new WP_Error;

if( !recaptcha_validate( $recaptcha ) ) {
    $reg_errors->add('field', 'Error, please enter the captcha again');
}

if( $user_reg_data['password'] !== $user_reg_data['password_confirmation']) {
    $reg_errors->add('field', 'Password mismatch');
}

if( $user_reg_data['email'] !== $user_reg_data['email_confirmation']) {
    $reg_errors->add('field', 'Email addresses do not match');
}

$isset_email = get_user_by('email', $user_reg_data['email']);

if( $isset_email != false ) {
    $reg_errors->add('field', 'This email is already registered');
}

if( isset($_GET['user_airline']) and ($_GET['user_airline'] !== '') )
{
   echo "You did not fill out the required fields.";
}

if( isset($_GET['user_employee_number']) and ($_GET['user_employee_number'] !== '') )
{
   echo "You did not fill out the required fields.";
}

if ( !empty($reg_errors->errors)) {

    $error_string = $reg_errors->get_error_message();

} else {

    $first_name           = sanitize_user( $user_reg_data['first_name'] );
    $last_name            = sanitize_user( $user_reg_data['last_name'] );
    $useremail            = sanitize_email( $user_reg_data['email'] );
    $password             = esc_attr( $user_reg_data['password'] );
    $user_phone           = htmlspecialchars(esc_attr($user_reg_data['phone']));
    $user_state           = htmlspecialchars(esc_attr($user_reg_data['state']));
    $user_country         = htmlspecialchars(esc_attr($user_reg_data['country']));
    $user_airline         = htmlspecialchars(esc_attr($user_reg_data['airline']));
    $user_employee_number = htmlspecialchars(esc_attr($user_reg_data['employee_number']));
    $user_questions       = isset($_POST['questions']) ? htmlspecialchars(esc_attr($_POST['questions'])) : '';
    $userdata = array(
        'user_login' => $useremail,
        'user_email' => $useremail,
        'user_pass'  => $password,
        'first_name' => $first_name,
        'last_name'  => $last_name
    );

    $user_id = wp_insert_user( $userdata );

    if( is_int($user_id) && $user_id > 0 ) {

        $email = get_welcome_email_options();

        if(!empty($email['subject'])) {
            $subject = $email['subject'];
        } else {
            $subject = 'KVI Registration';
        }

        if(!empty($email['body'])) {
            $body = $email['body'];
        } else {
            $body = 'Hey! You have successfully registered on the KVI Travel! <br>' . get_site_url();
        }

        $headers = array('Content-Type: text/html; charset=UTF-8');

        wp_mail( $useremail, $subject, $body, $headers );

        update_user_meta( $user_id, 'agent_prismic_id', $agent );
        update_user_meta( $user_id, 'phone', $user_phone );
        update_user_meta( $user_id, 'user_state', $user_state );
        update_user_meta( $user_id, 'user_country', $user_country );
        update_user_meta( $user_id, 'user_airline', $user_airline );
        update_user_meta( $user_id, 'user_employee_number', $user_employee_number );
        update_user_meta( $user_id, 'questions', $user_questions );

        $is_subscribed = isset($_POST['subscribed']) ? 1 : 0;

        update_user_meta( $user_id, 'subscribed', $is_subscribed );

        update_user_meta( $user_id, 'user_moderated', 0 );

        $added_user_data = [
            'id' => $user_id,
            'name'  => $first_name . ' ' . $last_name,
            'email' => $useremail,
            'phone' => $user_phone,
            'location' => $user_country,
            'airline' => $user_airline,
            'num' => $user_employee_number,
            'agent' => $agent,
        ];

        send_to_admin_email_about_new_registration( $added_user_data );

    }
}

And here is the LIVE form:

Authorize

The issue we are having is that the fields “Airline” and “Employee Number” sometimes come as blank fields in the admin notification email.

I have tried using the following that I found here on Stack Overflow:

<script>
jQuery(document).ready(function ($) {
        jQuery( '#form-registration .disspace' ).keydown(function(e) {     
            if (event.key === ' ') {
                return false;
            }       
        });
 });
</script>

Where I applied the css class .disspace to those fields.. that seems to work in the sense that I cannot hit the space bar once or more times to insert blank spaces.

But I have NO idea how people are able to submit the form where those fields come out blank.

Can anyone review this and help me? Thank you!

New contributor

Elyssa is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật