Search code examples
phpformsvalidationspamspam-prevention

How to validate name field to avoid numbers


How can I easily validate the name input on the form using bootstrap or php? I want this field to reject all numbers 0-9. Can you please help me out?

Here is the field, which is a part of the form I use:

<input class="form-control" id="name" placeholder="NAME" type="text" name="name">

And this is the php script which sends the form:

<?php
 $adresdo = "info@takelake.com";
  $temat = "Newsletter signup";
  $zawartosc = "Imie: ".$_POST['name']."\n"
       ."Email: ".$_POST['email']."\n"
       ."Selected".implode($_POST['checkbox'],",");

// if the url field is empty 
if(isset($_POST['url']) && $_POST['url'] == ''){

  if(!$_POST['name'] || !$_POST['email']){
     header("Location: error.html");
   exit;
}
$email = $_POST['email'];
if(mail($adresdo, $temat, $zawartosc, 'From: Subskrybent <'.$email.'>'))
{
   header("Location: ok.html"); 
}


} 

   header("Location: error.html");
  ?>

Solution

  • you can use html5 code for this and this will allow space and if you want to check at least 2 character then use [a-zA-Z][a-zA-Z ]{2,} or use [a-zA-Z][a-zA-Z ]{1,}

    <input type="text" name="name" pattern="[a-zA-Z][a-zA-Z ]{2,}" required>
    

    and this not allow space

     <input type="text" name="name" pattern="[a-zA-Z]{1,}" required>
    

    for more information

    https://www.w3schools.com/tags/att_input_pattern.asp

    and this is php validation

    <?php
    $adresdo = "info@takelake.com";
    $temat = "Newsletter signup";
    $zawartosc = "Imie: " . $_POST['name'] . "\n"
        . "Email: " . $_POST['email'] . "\n"
        . "Selected" . implode($_POST['checkbox'], ",");
    
    // if the url field is empty
    if (isset($_POST['url']) && $_POST['url'] == '') {
        // then send the form to your email
        mail('you@yoursite.com', 'Contact Form', print_r($_POST, true));
    
        if (!$_POST['name'] || !$_POST['email']) {
            header("Location: error.html");
        }
        if (preg_match('~[0-9]~', $_POST['name'])) {
            header("Location: error.html");
            exit();
        }
    
        $email = $_POST['email'];
        if (mail($adresdo, $temat, $zawartosc, 'From: Subskrybent <' . $email . '>')) {
            header("Location: ok.html");
        }
    }