I have a pattern match here that looks like it should work fine. However any input I give makes the conditional fail. I will handle the '99999-9999' case after I get the '99999' case working.
$ZipCode is a textfield that is being submitted on POST.
$ZipCode = $_POST["ZipCode"];
if(!preg_match("/^[0-9]{5}$/", $ZipCode))
{$error_str .= "The zip code you enter must be in the form of: '99999' or '99999-9999'\n";}
if(isset($_POST['submit']))
{?><script>var error = <?= json_encode($error_str);?>;
alert(error);
</script>
<?}
'11111' fails and '111111' also fails
Your code should work correctly. Example:
$ZipCode = "111111";
if(!preg_match("/^[0-9]{5}$/", $ZipCode))
{
echo "Incorrect format";
}
Result:
Incorrect format
Try entering some invalid input to see if the error message is displayed.
To handle both cases at once you can use this regular expression:
/^[0-9]{5}(?:-[0-9]{4})?$/
Related
I have an HTML form with PHP error checks. The form has several different types of fields (one for name, email, phone number, a checkbox, a drop down, etc.) and I have a PHP function written for each that runs when you hit the submit button, and checks that the form is filled in correctly and fully. If a field is left empty, or is filled in incorrectly, an error message appears. However, after I got that running, I tried to add a redirect, so that after the form is completed and submit is pressed, it brings the user to a confirmation page, if the errorchecks are passed. I wrote it like this:
if(isset($_POST['submit']) ){
header("Location:confirmed.php");}
It does what it's supposed to--bring the user to a new page--but it doesn't take into consideration any errorchecks. So, when submit is pressed, rather than run through the error checks, it immediately goes to the new page. I tried adding a variable named "errorcount" so each function so that the number of errors that occur when the form is submit will be either counted, or removed from the count, and then considered when changing the page...
if(isset($_POST['submit']) ){
if ($errorcount == 0){
header("Location:confirmed.php");}}
This didn't work either. I realized that $errorcount wasn't actually being updated at all; for what reason, I'm not sure. I set it up so each function returns $errorcount, and then called each function in the snippet of code above before running the second if statement, but it still does nothing.
I feel like I'm approaching this the wrong way, but I'm not really sure how else to do this. Please tell me if there's an easier way to achieve this, or maybe you have an idea what I'm doing wrong in the first place.
EDIT:
I am passing the variable $errorcount as global in each function, like so:
function validateName ($name, $submit){
global $errorcount;
if( empty( $submit )) {
return '';}
if (empty ($name)){
return "You didn't enter your name!";
$errorcount = $errorcount+1;
}
if (!preg_match("/^[a-zA-Z \-]*$/",$name, $matches)){
return "Please enter a valid name";
$errorcount = $errorcount+1;
}
else{
$errorcount = $errorcount-1;
}
return $errorcount;
}
However, $errorcount still does not actually change with the if loop I posted above. If I take that out (the section of code that causes the page to change) then the functions work as intended; once you click submit, the page refreshes, and error messages appear where the user did not fill out the form properly. But once all the form areas are filled out properly, clicking submit does... nothing.
EDIT 2:
I got it working. It's honestly not very efficient but it does what I need it to do. Thanks to all who helped!
You don't really need to count the errors, and you don't need to use global. Just write your validator functions so they return an error message if there is an error, or nothing if there is no error. Like this, for example:
function validateName($name) {
if (!$name) {
return 'name is required';
}
if (!preg_match("/^[a-zA-Z \-]*$/", $name)) {
return "Please enter a valid name";
}
}
Then when you run your validators, add any error messages you get to an array.
if ($error = validateName($_POST['name'] ?? '')) {
$errors['name'] = $error;
}
After you run all the validators, if the error array is empty, then there were no errors so you can redirect. And if it's not empty, then you have an array of errors keyed by field name, so you can display any errors next to the problematic fields, which your users will prefer rather than getting one error at a time in some generic location.
if (empty($errors)) {
// redirect
} else {
// stay here and show the errors
}
You're needlessly complicating things. Defining functions are only useful if you plan on re-using that code elsewhere. Try this instead:
if ( isset($_POST['submit']) )
{
if ( empty($name) )
{
echo "You didn't enter a name!";
sleep 3;
// redirect or re-load the form
}
elseif ( !preg_match("/^[a-zA-Z \-]*$/", $name, $matches) )
{
echo "Enter a valid name!";
sleep 3;
// redirect or re-load the form
}
header("Location:confirmed.php");
}
I currently have this code below which validates username length only. If none entered it will show error message, if less than 3 characters entered show error message. I want to add an if/else statement that if the user enters special characters like !##$%^&*()+=/? etc... the only special character is allowed is underscore (_) and hypen (-)... Help me how.
thanks
here's the code i have:
<?php
$serror="";
if (isset($_POST['submit'])) {
$username=$_POST['username'];
$lengt = strlen($username);
if($lengt == 0){
$serror=" Please enter account username ";
}
else{
if($lengt < 3 ){
$serror=" Please enter valid account username ";
}
}
if($serror==""){
ob_start();
echo "Success";
header("Location:progress.php?username=$username");
exit;
ob_end_flush();
}
else{}
}
?>
use preg_match() function
$yourString = "blahblah";
if (preg_match('/^[A-Za-z0-9_-]*$/', $yourString)) {
#your string is good
}
remeber preg_match() returns boolean
Your php script works after the user submits the form. From your tags in the question I assume you can use javascript. With Javascript you catch these errors before the form is submitted.
So, your html input field would fire a script and you can use the onkeypress event to see the value of the keystroke.
The submit button would also have a javascript event to look for min string length, else give warning and not submit form.
As others already pointed out, you should use regular expressions for this.
Try with the following if-statement (allows a-z, numbers, underscores and hyphens). It also checks that the length is at least 3 characters:
if (!preg_match("/^([\w\-]{3,})$/", $username)) {
$error = "Not enough chars or there are invalid ones".
}
Read more about preg_match() here
is it possible to do this , im trying to validate a form then, it will redirect using header() if TRUE.. but it seems not to be working? or my method is completely wrong ?
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$email = $_POST["clientEmail"];
if ($email != $sentEmailClients) {
echo 'Please enter a valid email';
} else {
$newURL = "http://www.myurl.com";
header('Location: ' . $newURL);
}
}
Give us more details about what actually happens when you run your code. You're likely facing one of the following problems:
You're using header() after you've already sent output to the browser. Headers must be sent before any other output. Check out the docs. If you change that line with die('redirecting') and that text shows up, then this is your problem.
Request method is not POST. Add die($_SERVER['REQUEST_METHOD']). If something other than POST is printed, then this is your problem.
$_POST['clientEmail'] is not set, or is not equal to $email
$email is not what you expect (where does it come from?)
$sentEmailClients is not what you expect (where does it come from?)
Basically, "why doesn't it work?" is not a good question because it doesn't give us much info with which to help you. Be more specific about what is happening.
Show enough of your code that we understand the origin of the variables you use.
Hi It seems that Your outermost if condition is not working thats why your header function is not working i just tried this and it woks fine. That means either your first if condition is false or either second if condition becomes true every time just try to echo your values before checking them.
<?php
if (1) {
$email = $_POST["clientEmail"];
if (0) {
echo 'Please enter a valid email';
} else {
$newURL = "http://www.google.com";
header('Location: ' . $newURL);
}
}
check this print_r($_SERVER["REQUEST_METHOD"]); is POST or not and
$email != $sentEmailClients true or false
I am just trying to check if a form variable is empty. The code sets the variables $getsubject and $getsubject to the $_POST of the form, then I am checking if they are, empty and if they are I want to set them to "No Message" or "No Subject". I tried with isset as well and it didn't work. I even tried setting an else statement that does the same thing and it doesn't change it.
$getsubject = $_POST['subject'];
$getmessage = $_POST['message'];
if(empty($getsubject)) {
$getsubject = "<No Subject>";
}
if(empty($getmessage)){
$getmessage = "<No Message>";
}
I found the problem .. the code is working - however the since there were brackets "<" and ">" ... when I retrieved the data from the SQL table, it was not appearing. Not sure why, but when I removed the brackets it worked.
If you are not sure id the data from the form exist you must use !isset to check it before you declare the variables, so:
if(!isset($getsubject)) {
$getsubject = "<No Subject>";
}
else{
$getsubject = $_POST['subject'];
}
if(!isset($getmessage)){
$getmessage = "<No Message>";
}
else{
$getmessage = $_POST['message'];
}
The data from $_POST['subject'];, for example, might not exist, and if you declare it php will give you an error
I suggest that you use a full if conditional to display the results you are looking for combined with html.
IF subject has content
then echo Great subject
ELSE
then echo No Subject
END IF
IF message has content
then echo Thank You for the message
ELSE
then echo No Messgae was entered
END IF
^this is the basic logic not the code
Also look into the trim php code which will trim blank space off of the submission. This helps eliminate blank responses or spaces counting as characters (will not remove space between characters)
I would like to accept only small and capital letters from the user.
I tried the below code, it echoes the invalid character message but doesn't work. I mean it doesn't check. It just displays the 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 insert the name to database. if numbers found in the name reject the name by displaying the error message else if the name contains only letters insert it into database. That's all I want to acheive.
<?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();
}
}
?>
If you just want to check you could use ctype_alpha() but you said you want to ACCEPT only letters so if you choose to accept the input you could:
$fname=preg_replace('/[^a-z]/i','',$fname);
better after the check
if(!isset($_POST['fname']) || !ctype_alpha($_POST['fname'])){
// can i haz alpha letters only?
}
(reference)
There are several issues with the code, and the one you are stuck with is probably that you have the form and its processing in the same PHP file. That’s possible, but it requires a different approach. For a starter, it’s probably better to separate them.
What happens with the code posted is that the PHP processor tries to process the form data when no form has been submitted, without even checking for the presence of the data. Now $fname is undefined, so the test always fails.
The test is wrong, too. Now it only checks whether $fname contains at least one letter. For example, if(!preg_match ('/^[a-zA-Z]+$/', $fname)) would test that $fname consists of one or more Ascii letters and nothing else.
use this , this is giving me correct answer
if(!preg_match ('/^([a-zA-Z]+)$/', $fname)){
echo "Invalid characters";
}
else{
echo "correct";
}
The general idea of checking for characters that don't match the [a-zA-Z] pattern is a good one.
However, the "not" part of your if condition is in the wrong place if you want this to work. What you've got now just makes sure that any single character in fname is an upper- or lower-case Latin letter.
You want to push the "not" part of the logic into the pattern:
if (preg_match('/[^a-zA-Z]/', $fname)) {
This checks if any character in fname is not a Latin letter, which is what you're trying to do.
Edit: Your new update has a different test that also works (it appears to be from sourcecode's updated answer, but you've got several tests from the different answers here that will work equally well). But, your updated post makes it clear that your problem isn't really with the pattern for testing the name.
Your code looks like this:
if (/* invalid fname */) {
echo "Invalid characters";
}
if (/* empty fname */) {
echo '<span> First name is required</span>';
}
else {
/* insert into database */
}
That else clause only depends on the the if that comes immediately before it: the check whether fname is empty. In other words, regardless of the result of your check against the characters of fname, you insert it into the database whenever it's not empty.
One easy way to fix this is to just change your second if to an elseif. This will chain all three conditionals together, so the final else block will only occur if both of the earlier conditionals that print error messages weren't triggered.
if (/* empty fname */) {
echo 'First name is required.';
}
elseif (/* invalid fname */) {
echo 'Invalid characters';
}
else {
/* insert into database */
}