I have a product upload form and 1 of the fields is a product description which is basically a textarea field. Everything about the form work except for even after you fill it out it won't go to the database because I keep getting an error for the "product description" field. It's saying that according to the preg_match I'm putting in the wrong characters. Right now the preg_match is allowing only letters and white space but for some reason it's not going through. However, I need the preg_match to allow letters, numbers, white space and special characters. Can someone help me write a preg_match that allows all 4 of these and also tell me why it's not working right now as is. Below is the code.
if (empty($productDescr)) {
$productDescrError = "Product Description is required";
echo "<strong>" .$productDescrError."</strong><br/>";
$hasError = true;
} // line closes if statement
else {
$productDescr = test_input($_POST["productDescr"]);
if (!preg_match("/^[a-z][-\'a-z]+[a-z]$/i",$productDescr)) {
$productDescrError = "Only letters and white space allowed in <em>Product Description</em>";
echo "<strong>" .$productDescrError."</strong><br/>";
$hasError = true;
} // line closes if statement
} // line closes else statement
Related
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
I want to get better on not nesting if-satments so much and got some help from my brother about how to think. So the thougt here is to create a function that validates that all fields in an form is filled in and with allowed caracters.
But I'm an expert on nested if:s and I need some help to learn a better way of doing it. My question is how I can do the same check in the function instead? What can I use that is good practise? Can I do it with an array?
My nested if statment is here (I'm supposed to do this to a much bigger form later on):
// If the submit button has been clicked
if(isset($_POST["login"])){
// Checks if username-field is empty and if allowed characters are used
if(empty($_POST['user']) or !preg_match("/^[a-zA-Z0-9 ]*$/", $_POST['user'])){
$error = "You can't leave a field empty and you can only use letters, numbers and space.";
}else{
// Checks if password-field is empty and if allowed characters are used
if(empty($_POST['pass']) or !preg_match("/^[a-zA-Z0-9 ]*$/", $_POST['pass'])){
$error = "You can't leave a field empty and you can only use letters, numbers and space.";
}else{
// Code here
}
}
}
And this is the base for what I want to try to do instead:
function validate(){
// Code here
}
// If the submit button has been clicked
if(isset($_POST["save"])){
if(validate(/*vaibles for each of the fields in the form*/)){
}else{
}
}
As you asked for an example, check this:-
<?php
if(isset($_POST["login"])){
$error = validate($_POST);
if(empty($error) {
.....//your further processing code
}else{
// code to show your error at appropriate place.
}
}
function validate($dataArray){
$validateArray = $dataArray; // either asign to a new variable or you can use directly $dataArray
$errors = array();
if(empty($_POST['user']) or !preg_match("/^[a-zA-Z0-9 ]*$/", $_POST['user'])){
$errors['user'] = "You can't leave a field empty and you can only use letters, numbers and space.";
}
if(empty($_POST['pass']) or !preg_match("/^[a-zA-Z0-9 ]*$/", $_POST['pass'])){
$errors['pass'] = "You can't leave a field empty and you can only use letters, numbers and space.";
}
//......so on
return $errors;
}
?>
Note:- this is an example that how can you proceed. thanks.
How do I validate the first name to only contain a-z characters using php. I have the following at the moment:
if (empty($myFirstName)) {
echo "<p>Please enter your first name!</p>";
else if(!preg_match("/^[a-zA-Z]$/", $myFirstName)){
echo "Your first name can only contain letters!";
}
Here's a working code :
if (empty($myFirstName)) {
echo "<p>Please enter your first name!</p>";}
else if(preg_match("/[^a-zA-Z]/", $myFirstName)){
echo "Your first name can only contain letters!";
}
I did a little modification to the regex : I added a ^ in the group, and removed the anchors.
As a result, your regex will match any character which is not a letter, and display the error message if there is a match.
I strongly advice you to validate user input at least on server side, and on client side if you want to.
For an email validation, the html filter works on client side.
On server side, you can use pre-set PHP filters :
if(filter_var($email, FILTER_VALIDATE_EMAIL)){
echo "email OK";
}
FYI, there is a regexp matching emails according to the RFC2822 standards :
[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*#(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?
May be you can use
if(! ctype_alpha($myFirstName) )
{
//check for alphabetic inputs only
echo "Your first name can only contain letters!";
}
Php manual
Your if is incorrect.
!preg_match("/^[a-zA-Z]$/", $myFirstName)
will only hold true if $myFirstName is not a single alpha character
to ensure that $myFirstName is not any number of alpha characters, try
!preg_match("/^[a-zA-Z]*$/", $myFirstName)
I am trying to strip certain characters and keywords from a php form and not having much luck.
What I want is to a modular filter list to remove urls and certain keywords. At the moment I just want to remove http links while keeping allowed domains. In this case example.com
<?php //Check whether the form has been submitted
if (array_key_exists('check_submit', $_POST)) {
//Converts the new line characters (\n) in the text area into HTML line breaks (the <br /> tag)
$_POST['Comments'] = nl2br($_POST['Comments']); //Check whether a
$_GET['Languages'] is set
}
//Let's now print out the received values in the browser
echo "<br />{$_POST['Comments']}<br /><br />";
}
else
{
echo "You can't see this page without submitting the form.";
}
?>
I always use:
$data = "<b> some text ///, test</b>"
htmlentities(strip_tags(mysql_real_escape_string($data)));
Hope that helps!
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 */
}