I am making a phone number validator and all numbers should start with 168 and then followed by 9 digits 123456789.In total the phone number should only have 12 digits.
I have tried this
$phoneNumber = '168921500789';
if( preg_match( "/^\168[0-9]{9}$/", $phoneNumber ) ){
echo "Valid number";
} else {
echo "Invalid number";
}
When i run the script,the number is not valid.How can i make the script take only 12 digits that must start with 168?.
Your RegEx is wrong, there's an useless backslash before the 1. Correct:
/^168[0-9]{9}$/
Full code:
$phoneNumber = '168921500789';
if( preg_match( "/^168[0-9]{9}$/", $phoneNumber ) ){
echo "Valid number";
} else {
echo "Invalid number";
}
You had to remove 1 slash:
$phoneNumber = '168921500789';
if( preg_match( "/^168[0-9]{9}$/", $phoneNumber ) ){
echo "Valid number";
} else {
echo "Invalid number";
}
we using like this, with referred this link
public function validatePhoneNumber($number){
$formats = array(
'###-###-####', '####-###-###',
'(###) ###-###','####-####-####',
'##-###-####-####','####-####','###-###-###',
'#####-###-###', '##########', '#########',
'# ### #####', '#-### #####'
);
$format = trim(preg_replace('/[0-9]/', '#', $number));
return (in_array($format, $formats)) ? true : false;
}
Related
I am trying to validate a phone number using PHP, and would like to know if there's a way to do it with FILTER_SANITIZE_NUMBER_INT instead of regex.
I need the password to enforce the xxx-xxx-xxxx format (allows '-') and max length of 12 characters.
This is my code so far. Would this work to validate any number into the xxx-xxx-xxxx format?
$phone = clean_input($_POST["phone"]);
if (empty($phone)) {
$phoneErr = "Valid phone number required";
$isValid = false;
} else {
if (!filter_var($phone, FILTERSANITIZE_NUMBER_INT)) ;
$phone_to_check = str_replace("-", "", $filtered_phone_number);
if (strlen($phone_to_check) < 10 || strlen($phone_to_check) > 12) {
$isValid = false;
}
}
I would use preg_match instead as you can cover all your needs in one statement. This regex assures that the value must have 10 digits, with optional - after the third and sixth digits.
$phone = clean_input($_POST["phone"]);
$isValid = preg_match('/^\d{3}-?\d{3}-?\d{4}$/', $phone);
Demo on 3v4l.org
I prefer using preg_match() functions for this style of regex.
An example based on your pattern
$phone = '000-000-0000';
if(preg_match("/^[0-9]{3}-[0-9]{3}-[0-9]{4}$/", $phone)) {
// $phone is valid
}
For validating using FILTER_SANITIZE_NUMBER_INT() try code below
function validate_phone_number($phone)
{
$filtered_phone_number = filter_var($phone, FILTER_SANITIZE_NUMBER_INT);
if (strlen($filtered_phone_number) < 12) {
return false;
} else {
return true;
}
}
Now below is the usage of the function that we have just created:
$phone = "444-444-5555";
if (validate_phone_number($phone) == true) {
echo "Phone number is valid";
} else {
echo "Invalid phone number";
}
first of all I'm using latest WordPress and CF7 version. I want to include the minlength validation for the tel field before. I know the syntax minlength=""
can be used inside the CF7, but for unknown reason, it won't work. Only maxlength="" is ok.
I already contacted the plugin support, but seems like no further response. So, I search here and found some code and I edit it so that the field will return an error if user put less than 10 characters. I put the codes inside functions.php
function custom_phone_validation($result,$tag){
$type = $tag['type'];
$name = $tag['name'];
if($name == 'Subject'){
$phoneNumber = isset( $_POST['phonenumber'] ) ? trim( $_POST['phonenumber'] ) : '';
if($phoneNumber < "9"){
$result->invalidate( $tag, "phone number is less" );
}
}
return $result;
}
add_filter('wpcf7_validate_tel','custom_phone_validation', 10, 2);
add_filter('wpcf7_validate_tel*', 'custom_phone_validation', 10, 2);
The result now is, it always display the "phone number is less" even though I insert more than 9 characters. May I know what wrong and how to solve it?
as I've tested you must have your tel field [tel* phonenumber tel-503] where phonenumber is name of postfield you are posting, second issue in your code is $name=='Subject' as you are validating tel so $name will be phonenumber. So it will be like this:
function custom_phone_validation($result,$tag){
$type = $tag['type'];
$name = $tag['name'];
if($name == 'phonenumber'){
$phoneNumber = isset( $_POST['phonenumber'] ) ? trim( $_POST['phonenumber'] ) : '';
if(strlen($phoneNumber) < 9){
$result->invalidate( $tag, "phone number is less" );
}
}
return $result;
}
add_filter('wpcf7_validate_tel','custom_phone_validation', 10, 2);
add_filter('wpcf7_validate_tel*', 'custom_phone_validation', 10, 2);
Your $phoneNumber is a string. You will need to get the length of the string to compare with 9.
Your code will become:
function custom_phone_validation($result,$tag){
$type = $tag['type'];
$name = $tag['name'];
if($name == 'Subject'){
$phoneNumber = isset( $_POST['phonenumber'] ) ? trim( $_POST['phonenumber'] ) : '';
if(strlen($phoneNumber) < 9){//<=====check here
$result->invalidate( $tag, "phone number is less" );
}
}
return $result;
}
add_filter('wpcf7_validate_tel','custom_phone_validation', 10, 2);
add_filter('wpcf7_validate_tel*', 'custom_phone_validation', 10, 2);
So in the form I have this input
<input type="text" name="squareFoot" value="<?PHP if(isset($_POST['squareFoot'])) echo $squareFoot ?>"><span class="error_message"><?PHP echo " " . $squareFootError; ?></span>
And here's my validation (which is yes above the form)
if(isset($_POST['submit'])){
$isSubmitted = true;
$squareFoot = $_POST['squareFoot'];
$squareFoot = filter_var($squareFoot, FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION);
$squareFoot = filter_var($squareFoot, FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_THOUSAND);
$squareFoot = filter_var($squareFoot, FILTER_SANITIZE_SPECIAL_CHARS);
if(!is_numeric($squareFoot)){
$isValid = false;
$squareFootError = "Please enter a numeric value";
}
else if(empty($squareFoot)){
$isValid = false;
$squareFootError = "Please enter a numeric value";
}
else if($squareFoot < 200){
$isValid = false;
$squareFootError = "Please enter a number between 200 and 500,000";
}
else if($squareFoot > 500000){
$isValid = false;
$squareFootError = "Please enter a number between 200 and 500,000";
}
else{
/// do math (code not shown)
// Format Square Footage
$squareFootFormat = number_format($squareFoot, 0, '', ',');
// Display to user
<p>1. Square Footage being stripped <span class="right_al"><?PHP echo $squareFootFormat; ?></span></p>
So I have it set up so that the user can't put in html or script, the user must put in a number that has to be between two numbers, and that number can have a comma.
I also want the user to be able to put in something like 500.5, but when testing 500.5 turns into 5,005.
Is it because of
$squareFootFormat = number_format($squareFoot, 0, '', ',');
Or is something else wrong with it?
I kinda want to keep the number_format() in because it makes the number easier to read if it's some large number like 100,000. Can I do that?
Thanks for helping.
Your filter_var is not going to allow 500.5 as a value.
$squareFoot = filter_var($squareFoot, FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_THOUSAND);
What about only doing this:
<?php
$squareFoot = $_POST['squareFoot'];
$smallest = 1;
$greatest = 100000;
if(is_numeric($squareFoot)) {
if($squareFoot < $greatest && $squareFoot > $smallest) {
//do what you want
echo number_format($squareFoot, 1, '.', ',');
}
else {
echo "Please enter a number between " .$smallest . " and ".$greatest;
}
}
else {
echo "Please enter a numeric value";
}
?>
Looks simplier to me.
I used to rely on is_numeric() for making sure data passed from users is numeric. I recently discovered that users can also pass data 0xFF (hexdec = 255).
I'd like to disallow anything that is not a whole number (and not a hex representation).
Here's what I've tried so far.
$i_haxors_u = $_GET['id'];
$regex = '/[0-9]*/';
if (!empty($i_haxors_u) && !preg_match($regex, $i_haxors_u))
{
echo '<p>Invalid $i_haxors_u ' . strip_tags($i_haxors_u);
} else {
echo '<p>$i_haxors_u is numeric... maybe.';
}
This is still giving values like 0xFF a pass. How do I allow non-hex numbers only?
UPDATE Nov 12 2014.
Note that the selected answer works fine for data passed via GET, but will not work if a variable is set to a hex value.
$x = 0xFF;
if (is_numeric($x))
{
echo "<p>$x is a number.";
} else {
echo "<p>$x is not a number.";
}
if (preg_match('/^[\d]+$/',$x))
{
echo "<p>$x is a number.";
} else {
echo "<p>$x is not a number.";
}
$x = '0xFF';
if (is_numeric($x))
{
echo "<p>$x is a number.";
} else {
echo "<p>$x is not a number.";
}
if (preg_match('/^[\d]+$/',$x))
{
echo "<p>$x is a number.";
} else {
echo "<p>$x is not a number.";
}
Prints
255 is a number.
255 is a number.
0xFF is a number.
0xFF is not a number.
use match non-digit in your regex: $regex = '/\D/';
assume failure and pass when confirming that no non-digits are present in the input.
following code succeeds on id =7, give fail on id = 7.2, 7.2x, ffff, 0xff, -1
$id = $_GET['id'];
//assuming failure:
$valid = false;
if (!preg_match('/\D/',$id)) { $valid = true; } //fail if containing non-digit
if ($valid) {
echo "$id provided is valid";
}
else {
echo "$id provided is not valid";
}
You need to use anchors and use + quantifier to only allow integers:
$regex = '/^\d+$/';
Using + quantifier will also let you take out !empty($i_haxors_u) condition since \d+ will enforce 1 or more digits.
It's just because you have to test all the number:
$regex = '/^[0-9]+$/';
no need to test empty with +
I am trying to learn Regular Expression in PHP by creating simple samples.Here I have very simple example as:
if($_POST){
$errors = array();
if(isset($_POST['name'])){
if(!preg_match('/^([a-zA-Z]{3,8})$/',$_POST['name'])){
$errors['name1'] = "Must enter Alphabet";
$errors['name2'] = ""Cant be less than 3";
}
}
if(count($errors)==0){
header("Location: pro.php");
exit();
}
}
?>
<form method="POST" target="">
First name: <input type="text" name="name"><br>
<input type="submit" name="submit">
</form>
To me, the validation is working fine but I have problem on presenting error message based on error.For example I would like to display error $errors['name1'] ONLY when not string has entered and $errors['name2'] while numbers entered.
I tried to separate expression into two criteria as:
if(isset($_POST['name']))
{
if(!preg_match('/^([a-zA-Z])$/',$_POST['name']))
{
$errors['name1'] = "Must enter Alphabet";
}
if(preg_match('/^{3,8}$/',$_POST['name']))
{
$errors['name2'] = "Cant be less than 3";
}
}
but I am getting following error
Update
if(isset($_POST['name']))
{
if(!preg_match('/^([a-zA-Z])$/',$_POST['name']))
{
$errors['name1'] = "Must enter Alphabet";
}
if ( ! preg_match( '/.{3,8}/', $_POST['name'] ))
{
$errors['name2'] = "Cant be less than 3";
}
}
The error you are seeing is the result of not specifying match criteria in the regex before the {} operator. If you only care whether at least three of ANY character had been entered, try
if ( ! preg_match( '/.{3,8}/', $haystack ) )
You have to provide an 'atom' for the range to count. In this case, '.' signifies any single character.
How about:
if (isset($_POST['name'])) {
if (preg_match('/[^a-z])/i', $_POST['name'])) {
$errors['name1'] = "Must enter Alphabet";
}
if ( strlen($_POST['name']) < 3) {
$errors['name2'] = "Cant be less than 3";
}
if ( strlen($_POST['name']) > 8) {
$errors['name3'] = "Cant be more than 8";
}
}
If you really want to use regex:
if (preg_match('/[^a-z])/i', $_POST['name'])) {
$errors['name1'] = "Must enter Alphabet";
}
if ( ! preg_match('/^.{3,8}$/', $_POST['name']) ) {
$errors['name2'] = "Cant be less than 3";
}
Ok I am going to answer my question.Thanks to Masud Alam I figure it out how to do this in Regular Expression. The hint is using
if (!preg_match('/^[a-z]+$/i', $_POST['name'])) {
//
}
if (!preg_match('/^.{3,25}$/', $_POST['name'])) {
//
}
it works for me so far!