how to make a function that validates fields in a form? php [closed]

Here is a simple implementation –

function validateUserName($uname){
  $illegalCharacters = array('!','@','#');

  // first check the length
  $length = strlen($uname);
  if ($length < 5 && $length > 10){
    return false;
  }else{
    // now check for illegal characters
    foreach($illegalCharacters AS $char){
      if (strpos($uname,$char) != -1){
        return false;
      }
    }
  }
  return true;
}

$userName = "user1905577";
if (validateUserName($username)){
  echo "Valid username!";
}else{
  echo "INVALID username!";
}

Lets see what is going on here –

We first use strlen() to test the length of the username and then iterate over all the illegal characters we defined and use strpos() to see if any appear in the username.

The function’s name is validateUserName and we can call it by simply placing it’s name and brackets afterwards. Like this – validateUserName(). This function has to receive a parameter (the username), so we pass that within the brackets, Like this – validateUserName($username)

Browse More Popular Posts

Leave a Comment