jquery – codeigniter form validation regex for whitespace not working

I have an input box in a form that can only be filled by alphanumeric, underscores, dashes, and dots. weird thing is I can successfully check if the input follows the rules in regex101 with this pattern /^(A-Za-z0-9._-)+$/, but when I apply the same pattern on my PHP code, the form validation doesn’t trigger an error when there’s a space at the end. here’s my code below:

this is the html:

<form action="" id="form1">
  <input type="text" name="username" id="username" value="<?php $this->input->post('username'); ?>">
  <button type="button" id="btnSubmit">Submit</button>

the form is posted using jquery (v3.3.1) ajax like this:

var myData = $('#form1').serializeArray();

  url: '/home/validate_inputs',
  type: 'POST',
  data: myData,
  dataType: 'json',
  success: function(res) {
    console.log('res', res);
  error: function(err) {
    console.log('error', responseText);

and here’s the PHP (v7.4.7) code:

public function validate_inputs()
  $rules = (
    'field' => 'username',
    'label' => 'Username',
    'rules' => 'required|callback__check_characters_username'

  if ($this->input->server('REQUEST_METHOD') == 'POST' && $this->form_validation->run())
    // do database process

  if ($this->input->is_ajax_request())
    $response = (
      'postdata' => $this->input->post(),
      'message' => validation_errors() ? : 'process completed successfully',
    echo json_encode($response);


public function _check_characters_username($val)
  if (preg_match("/^(A-Za-z0-9._-)+$/", $val))
    $this->form_validation->set_message('_check_characters_username', 'Forbidden characters!!');
    return false;

  return true;