Or do both: put the validation inside a function, and put the function inside a file.
<?php
function is_valid_name($name) {
return preg_match("/^[a-zA-Z\'\-\s]*$/", $name);
}
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
require_once "the other file.php";
if (!is_valid_name($firstname)) {
$firstnameErr2 = "Only letters allowed";
}
if (!is_valid_name($lastname)) {
$lastnameErr = "Only letters allowed";
}
Kinda. I'd say that you're going about it the naive and simplistic way. Which is typically the first step towards doing it in a smarter and more flexible way.
If you're doing this for a personal project then don't mind it. Unless you specifically want to learn how to do this better...?
But I will say one thing: don't validate people's names. Just don't. It's a bad practice because you're always going to end up rejecting the valid name of someone, somewhere. Additionally, separating names by first and last isn't even correct either: there are people with single names.
The right way to do names is to use a single full-name input and ensure it has something in it. Nothing more.