Allow only capital and small letters - php

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 */
}

Related

Invalid if Special Character is entered

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

How Mobile number validation varies with the URL?

I have written mobile number validation script as you can see in below.the problem it is working fine with the URL1.but not with the URL2.I want to know why is that?
URL1 - http://axbc.com/con/s2.php
URL2 - http://axbc.com/con/s2.php?key=d908e8401774411861043
Here is my Code
if(isset($_POST['btn-signup']))
{
$mobilenumber = $_POST['mobilenumber'];
if(!empty($dialogmobilenumber)) // phone number is not empty
{
if(preg_match('/^947\d{8}$/',$mobilenumber)) // phone number is valid
{
echo 'success';
}
else // phone number is not valid
{
echo "<script>alert('Mobile Number is Not valid.. Format should be ');
</script>";
}
}
}
Your code is working fine for me in both urls.
It is doing, what it is meant for, It is matching all the 11 digit numbers starting from '947'+8 nos.
As, you are not using the passed variable anywhere in this piece of code,So it can never be the cause of your error.
One thing,You are receiving mobilenumber as POST in $mobilenumber variable.
So,why are you using $dialogmobilenumber to check if it is empty or not ?
Have you defined this anywhere in the program.
if(!empty($dialogmobilenumber)) // phone number is not empty
{ ...
Another thing, Is your form also present in s2.php ?
If not, what is your action contains (action="?") for the form ?
Note: If you can paste the complete code and output that you are getting for
URL2, that will be good.

How to check if a field is not empty and with allowed caracters in an PHP function?

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.

PHP - Validating a registration form

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)

php - check an empty string with === '' does not work

When I test to see if the textarea in my form is empty to do a redirect so it doesn't submit it in php, it doesn't work.
The textarea is named $_POST['message'], I know the variable exists because if I do this statement;
if (isset($_POST['message'])) {
header('Location:/');
exit();
}
Then it always redirects back to the index page so the variable must exist, although if I do this;
if (empty($_POST['message'])) {
header('Location:/');
exit();
}
It does not work, also tried with all three combos of =/==/===
if ($_POST['message'] === '') {
header('Location:/');
exit();
}
And also...
if (empty(trim($_POST['message']))) {
header('Location:/');
exit();
}
Any ideas why this is happening? And how I can prevent it, I really need to stop it as I do not want empty values in my mysql table.
I did some research and it seems some other people have had this problem, but I have seen no answer as of yet.
You probably have some whitespaces in the string, which isn't stripped by trim().
Do a strlen() on it to see what's up, and then log it byte by byte (http://stackoverflow.com/questions/591446/how-do-i-get-the-byte-values-of-a-string-in-php).
One thing you could think about is to make sure your textarea doesn't have any content in the markup (spaces, linkebreaks, whatever), like this:
<textarea></textarea>
I'm pretty sure your last try would work if you'd do it correctly, this:
if (empty(trim($_POST['message']))) {
// ...
}
...is a syntax error. empty is a language construct and does not accept expressions. Try:
$message = isset($_POST['message']) ? trim($_POST['message']) : '';
if (empty($message)) {
// $_POST['message'] is empty
}
This will ignore all input lengths below 3 chars:
if (isset($_POST['message']) && strlen(trim($_POST['message'])) < 3) {
header('Location:/');
exit();
}
However, if you just want to check, if a form was submitted, ask for the submit-button:
<input type="submit" name="submit" value="send" />
the php code would be
if (!array_key_exists('submit', $_POST)) {
header('Location:/');
exit();
}

Categories