Allow only capital and lowercase letters

I would like to accept only small and capital letters from the user.

I tried the code below, it echoes an invalid character message, but it doesn’t work. I mean, he does not check. It just displays a message. Any help?

<form action="" method="post">
<input type="text" name="fname">
<input type="submit" value="Send" name="submit">
</form>

Update:, this is what I have to check and paste the name into the database. if the numbers found in the name reject the name, displaying an else error message, if the name contains only letters, insert it into the database. That is all I want to achieve.

<?php
if ( isset( $_POST['submit'] ) ) { 
$fname = $_POST["fname"];

if(!preg_match ('/^([a-zA-Z]+)$/', $fname)){
echo "Invalid characters";
}

if (empty($fname)) {
echo  '<span> First name is required</span>';
}

else{
$mysqli = new mysqli("localhost", "root", "", "test");
$stmt = $mysqli->prepare("INSERT INTO test (firstname) VALUES (?)");

$stmt->bind_param("s", $fname);
$stmt->execute();

$stmt->close();

$mysqli->close();


}
}
?>
+5
source share
5 answers

, ctype_alpha(), , , , , :

$fname=preg_replace('/[^a-z]/i','',$fname);

+6
if(!isset($_POST['fname']) || !ctype_alpha($_POST['fname'])){
  // can i haz alpha letters only?
}

()

+5

, , , , PHP. , . , , .

, , PHP- , , . $fname - undefined, .

. , $fname . , if(!preg_match ('/^[a-zA-Z]+$/', $fname)) , $fname Ascii .

+1

,

if(!preg_match ('/^([a-zA-Z]+)$/', $fname)){
    echo "Invalid characters";
}
else{
    echo "correct";
}
0

, [a-zA-Z], .

, "" if , , . , fname .

"" :

if (preg_match('/[^a-zA-Z]/', $fname)) {

, - fname , .

: , (, , , ), , .

:

if (/* invalid fname */) {
    echo "Invalid characters";
}

if (/* empty fname */) {
    echo  '<span> First name is required</span>';
}

else {
    /* insert into database */
}

else if, : , fname . , fname, , .

One easy way to fix this is to simply change the second ifto elseif. This will tie all three conditional expressions together, so the final block elsewill only occur if both of the previous conditions that print error messages have not been run.

if (/* empty fname */) {
    echo  'First name is required.';
}

elseif (/* invalid fname */) {
    echo 'Invalid characters';
}

else {
    /* insert into database */
}
0
source

All Articles