Mohammad Istanboli Mohammad Istanboli - 4 months ago 7x
PHP Question

Regex for form validation

hello I have a simple form to validate I already asked about a client side validation but the problem now is that server side validation isn't working the idea is to validate the input field and check if its length between [5-20] chars and display an error msg if not as well as preventing the form from submitting this should happen at the client side then if every thing is right the data should be sent to the server and the server will check if the input data contains just letters if yes then it will echo "thanks for submitting the form " and if not display the error message " the name should contain only letters from a to z" the problem is after the form being submitted and I get the ok from the client side validation I never get one of the server messages please help here is the code

$name = $_POST['user'];

if(!preg_match("/^[a-zA-Z ]*$/",$name))
echo "name must contain only characters";
echo "thanks for submitting the form";

<!doctype html>
<title>form validation</title>
<script src=""></script>

$( document ).ready(function()

$("form").on('submit', myfunction); //<-- listen for form submit, not button click

function myfunction(evt)
{ //<-- the event object is automatically passed along;
// this is key for suppressing submission
name = $("#user").val();
nameError = $(".error").first();
myNameError = "";

if(name.length < 5 || name.length > 20)
myNameError += "length should be between 5 and 20 ";
myNameError += "ok"

if (myNameError)
evt.preventDefault(); //<-- suppress submission if error found



color : red;
text-transform: capitalize;
margin-left: 20px;

<form method="post" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF'])?>">
NAME : <input type="text" name="user" id="user"><span class="error"></span><br />
<input type="submit" value="Submit" id="submit">



This is definitely a problem:

if (name.length < 5 || name.length > 20)
    myNameError += "length should be between 5 and 20 ";
    myNameError += "ok"

if (myNameError) 

You are setting the myNameError variable to a string, either the error message or the string ok. So if (myNameError) is always true so you will never make any POST request to the server.

To solve this problem, you should not add any string to myNameError when there is no error.