I am trying to validate a form before it is inserted into the db. First name, last name and email address. Email address works fine. It is the last name I am having a problem with, which also means I am having a problem with the first name.
The first and last name allow any characters at the moment, including numbers and symbols. where have I gone wrong?
if (preg_match('/^[A-Z \'.-]{2,45}$/i', $_POST['lname'])) {
$c_lname = escape_data($_POST['lname'], $dbc);
} else {
$c_lnameError = ("Please enter your last name!");
}
This is my validation, I am trying to use Regex to insist the value is between 2 to 45 characters and only contains a combination of upper and lower case letters, a space, a period, an apostrophe and a hyphen. Any help would be much appreciated.
PHP
<?php
$c_fnameError = $c_lnameError = $c_emailError = $c_phoneError = "";
if (isset($_POST['Update'])) {
$c_fname = $_POST['fname'];
$c_lname = $_POST['lname'];
$c_email = $_POST['email'];
$c_phone = $_POST['phone'];
//validate laste name
if (preg_match('/^[A-Z \'.-]{2,45}$/i', $_POST['lname'])) {
$c_lname = escape_data($_POST['lname'], $dbc);
} else {
$c_lnameError = ("Please enter your last name!");
}
// validate email
if (!filter_var($c_email, FILTER_VALIDATE_EMAIL) === false) {
} else {
$c_emailError = ("<b> Email is not a valid email address</b>");
}
$insert_det = "INSERT INTO Cus_acc_details(CUS_Fname,CUS_Lname,Cus_Email,CUS_Phone)
VALUES (?,?,?,?)
ON DUPLICATE KEY
UPDATE
Cus_acc_details.CUS_Fname = '$c_fname',
Cus_acc_details.Cus_Lname = '$c_lname',
Cus_acc_details.Cus_Email = '$c_email',
Cus_acc_details.CUS_Phone = '$c_phone'";
$stmt = mysqli_prepare($dbc, $insert_det);
mysqli_stmt_bind_param($stmt, 'sssi', $c_fname, $c_lname, $c_email, $c_phone);
/* execute query */
$r = mysqli_stmt_execute($stmt);
if ($r) {
echo "<script> alert('Saved')</script>";
} else {
echo "<b>Oops! we have an issu </b>";
}
}
?>
HTML
<form id="myform " class="Form" method="post" action="Cus_Account.php?c_id=<?php echo $c_id ?>" accept-charset="utf-8">
<!-- <div id="first">-->
<input type="text" id="fname" name="fname" value="<?php echo $_SESSION['fname']; ?>" required>
<input type="text" id="lname" name="lname" value="<?php echo $_SESSION['lname']; ?>" required>
<input type="text" id="email" name="email" value="<?php echo $_SESSION['Cus_Email']; ?>" required>
<!-- Onclick only accept numbers between 0-9-->
<input type="tel" id="phone" name="phone" value="<?php echo $_SESSION['phone']; ?>" onkeypress="return IsNumeric(event);" ondrop="return false;" onpaste="return false;" required>
<!-- id = phone error messge-->
<span id="error" style="color: Red; display: none">Oops! I can only accept numbers</span>
<input type="submit" name="Update" value="Update">
<br>
</form>