• PHP Help
  • how do you only allow letters and not symbols into a text field in php

I have a section of code where I am wanting an error to occur when a user enters symbols and not letters into the name and lastname of the form fields. The email is working correctly when a user enters an invalid email address but it won't currently display an error if the user enters symbols in the name fields. I have attached code below, any help appreciated. Thank you

		<?php
				// define variables and set to empty values
				$nameErr = $lastErr = $emailErr = "";
				$name = $last = $email = "";

				if ($_SERVER["REQUEST_METHOD"] == "POST") {
					if (empty($_POST["name"])) {
						$nameErr = "First Name is required";
					} else {
						$name = test_input($_POST["name"]);
						// check if name only contains letters and whitespace
						if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
							$nameErr = "Only letters and white space allowed"; 
						}
					}
					echo $nameErr;

					if (empty($_POST["last"])) {
						$lastErr = "Last Name is required";
					} else {
						$last = test_input($_POST["last"]);
						// check if name only contains letters and whitespace
						if (!preg_match("/^[a-zA-Z ]*$/",$last)) {
							$lastErr = "Only letters and white space allowed"; 
						}
					}
					echo $lastErr;
					
					if (empty($_POST["email"])) {
						$emailErr = "Email is required";
					} else {
						$email = test_input($_POST["email"]);
						// check if e-mail address is well-formed
						if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
							$emailErr = "Invalid email format"; 
						}
					}
					echo $emailErr;
				}

?>

<div class="article"><div class="box-sizing">
<h1>Alert Registration</h1><div class="" id=""><ul>
<p>Register to recieve alerts about shark catches in your chosen area</p>
	
	<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
	<section class="user-details">
		<label for="name">First Name:</label><br>
			<input name="name" type="text" size="35" value="">
				<span class="error">* <?php echo $nameErr;?></span>
			<br><br>
		<label for="last">Last Name:</label><br>
			<input name="last" type="text" size="35" value="">
				<span class="error">* <?php echo $lastErr;?></span>
			<br><br>
		<label for="email">Email Address:</label><br>
			<input name="email" type="email" size="35" value="">
				<span class="error">* <?php echo $emailErr;?></span>
			<br><br>
		<label for="phone_number">Phone Number:</label><br>
			<input name="phone_number" type="tel" size="35" value="">
			<br><br>
		<label for="password">Password</label><br>
			<input name="password" type="password" size="36" value="">
			<br><br>
	</section>
</div>

    The posted code does display the "Only letters and white space allowed" errors when you enter wrong characters in those fields. Either you didn't save your code or you made a change to the form but didn't reload the page to get the changes into the browser.

    This code is based on w3schools crap and is filled with unnecessary logic that has you doing busy-work/make-work things instead of actually programming. It also has a logic mistake. It is validating a different value in the empty() test than it is using in the rest of the code, so, a value consisting of all space characters is considered valid. Do you really want your code to do that? The 'test_input' function is unconditionally stripping slashes (when this was needed it should have been conditionally applied) and it is improperly applying htmlspecialchars() to input data. Htmlspecialchars() is an OUTPUT function. It should actually be htmlentities() and you apply it only when you output data onto a web page.

    Here is what your form processing code should be doing -

    1. Use two arrays, one to hold a trimmed working copy of the form data, and one to hold the validation error messages.
    2. Inside the form processing code, get trimmed copy of all the form data at once using php's array_map() function, with php's 'trim' function as the call-back function. You would use the contents of this array in the rest of the code, which would mean that you are testing/using the same value from any particular form field throughout the rest of the code.
    3. When you validate the input data, store validation errors in the second array, using the field name as the array index. This error array is also an error flag. If the array is empty, there are no errors and you can use the form data. You can test/display the content of this array at the appropriate location(s) in the html document.
    4. After the end of the validation logic, test if the errors array is empty. If it is, use the submitted form data.
    5. At the end of the form processing code (the code using the form data can set errors), if there are no errors, redirect to the exact same url of the page to cause a get request. Otherwise, let the code continue to run and (re)display the form. You should also re-populate the form field values with the submitted form data (this was mentioned your previous thread.)
      20 days later

      Weedpacket Please, PLEASE, don't name your children with curse words. 😉

      Interesting article.

        3 months later

        <input name="name" type="text" size="35" value="" class="yazibolum" required />

        <script>
        $(".yazibolum").keyup(function (){
        if (this.value.match(/[^a-zA-Z]/g)){
        this.value = this.value.replace(/[^a-zA-Z]/g,'');
        }
        });
        </script>

          Write a Reply...