PHP - Validating a registration form - php

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)

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.

PHP Checking ctype and strlen in single if statement

I have a form that validates First Name, Last Name, and E-mail before processing. It seems however that something isn't working. If I enter an e-mail address and my script validates it, then the page continues regardless of the checks I have in place for First and Last Name.
HTML Form Inputs
First Name <input type="text" id="new_user_fn" name="new_user_fn">
Last Name <input type="text" id="new_user_ln" name="new_user_ln">
PHP Script
$ec = 0;
$fn = trim($_POST['new_user_fn']);
$ln = trim($_POST['new_user_ln']);
if(!ctype_alpha($fn) OR strlen($fn) <= 0){
$error = "First Name cannot be blank and may only contain letters";
$ec++;
}
if(!ctype_alpha($ln) OR strlen($ln) <= 0){
$error = "Last Name cannot be blank and may only contain letters";
$ec++;
}
Essentially this checks if the $fn is alphabetic and greater than 0 in length to ensure the user filled out the input with valid text. I go on to verify the e-mail address (this part works correctly so it has been omitted from the post) and check the value of $ec.
if($ec > 0){
die($error);
}else{
// Finish Processing
}
So if I leave the inputs for "fn" and "ln" blank but supply a valid e-mail address, the script still executes as if $ec = 0.
Am I missing something simple?
Lukas found the issue above. Another $ec = 0 existed that was not commented out. Removing it solved the problem. Thanks all. Always nice to have an extra set of eyes sometimes. Much appreciated!

Allow only capital and small letters

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

validate function for special characters for prescribed data in url in php , CodeIgniter

http://localhost/sssss/sss.php&send=90&msg=z a data c
guys i need to validate for the particular data which is in the url... validate function should be able to check for special characters only for that data ... how to achieve this....
i need to validate in such a manner that no special characters will be in included along with the data.... and the url is how we use for recharging so spaces everything will be included
Use this:
$msg = $_GET['msg'];
list(,,,$amount,) = explode(" ", $msg);
if(preg_match("/^\\d+$/", $amount))
echo "valid amount!";
else
echo "invalid amount";
Hope this helps. Cheers

Categories