Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 = "[email protected]";
  $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");
  ?>
like image 822
Piotr Ciszewski Avatar asked Jan 31 '26 12:01

Piotr Ciszewski


1 Answers

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 = "[email protected]";
$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('[email protected]', '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");
    }
}
like image 183
Shafiqul Islam Avatar answered Feb 02 '26 02:02

Shafiqul Islam



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!