I recently switched a input form from a text to a textarea so that I could have multiple lines of text.
The form is working fine except when I go to validate. If it is one line, there is no problem but when I enter text that wraps to the second line, i get an error from my form validator (only letters and numbers are allowed) here is my code:
private function validate_alnum($var, $min=0, $max=0, $required=false, $err="") {
if($required==false && strlen($this->source[$var]) == 0) {
return true;
}
if(isset($this->source[$var])){
if(strlen($this->source[$var]) < $min) {
$this->errors[$var] = $err . ' is too short. It has to be at least '.$min. ' character(s)';
} elseif(strlen($this->source[$var]) > $max) {
$this->errors[$var] = $err . " is too long. It can't be more than ".$max. " characters";
} elseif(!preg_match("/^[a-zA-Z0-9 -.:,]*$/", $this->source[$var])) {
$this->errors[$var] = $err . ' is invalid. Only letters and numbers are allowed';
}
}
}
Your regex doesn't allow new lines. Try:
^[-a-zA-Z0-9\s.:,]*$
also - should be the first or last character if you want it to be literal, otherwise it makes a range.
The \s here will allow for single spaces, new lines, and tabs. ( Additional reading on the \s)
If you change the quantifier to + you can be sure there is more than 1 character in the string, which would take out your default $min requirement (the error message would be less specific though).
Related
I am trying to validate 10 digits mobile number using PHP function preg_match. The below code does not produce any output.
Is it the regex wrong? or I am using it incorrectly.
I was expecting Hi True in the output. if it matches or Hi False if it does not match.
<?php
$value = '9987199871';
$mobileregex = "/^[1-9][0-9]{10}$/" ;
echo "Hi " . preg_match($mobileregex, $value) === 1; // #debug
?>
regex taken from https://stackoverflow.com/a/7649835/4050261
The regex you stated will match eleven digits, not ten. Since all Indian mobile numbers start with 9,8,7, or 6, we can use the following regex:
^[6-9][0-9]{9}$
Here is your code snippet updated:
$value = '9987199871';
$mobileregex = "/^[6-9][0-9]{9}$/" ;
echo "Hi " . preg_match($mobileregex, $value) === 1;
Note that the above regex is still probably far from the best we could do in terms of validation, but it is at least a start.
The following code snippet will check if the mobile number digits are within 10-15 digits including '+' at the start and followed by a non-zero first digit.
Regular expression
"/^[+]?[1-9][0-9]{9,14}$/"
Code snippet
// Validation for the mobile field.
function validateMobileNumber($mobile) {
if (!empty($mobile)) {
$isMobileNmberValid = TRUE;
$mobileDigitsLength = strlen($mobile);
if ($mobileDigitsLength < 10 || $mobileDigitsLength > 15) {
$isMobileNmberValid = FALSE;
} else {
if (!preg_match("/^[+]?[1-9][0-9]{9,14}$/", $mobile)) {
$isMobileNmberValid = FALSE;
}
}
return $isMobileNmberValid;
} else {
return false;
}
}
^ symbol of the regular expression denotes the start
[+]? ensures that a single(or zero) + symbol is allowed at the start
[1-9] make sure that the first digit will be a non zero number
[0-9]{9,14} will make sure that there is 9 to 14 digits
$ denotes the end
$mob = "9513574562";
if(preg_match("/^\d+\.?\d*$/",$mob) && strlen($mob)==10){
echo 1;
}else{
echo 0;
}
preg_match() checking it is integer or not and in strlen() it is checking no of digit in this string. If 2 condition satisfy then it is a 10 digit valid mobile no
for pakistani mobile number the regex code will be the following
^[9][2][3][0-9]{9}$
Building a php calculator application and I'm a little confused on how I would do a specific case.
In general, I'm checking the input via a regular expression using preg_match but
what I'm confused about is how to cover the case of 09+0, I want to make sure that no number has a zero and then a number to the right of it.
On the left, it can be anything other than / sign. Some more examples include the following : 01+100, 33+011 etc (essentially, I want to let the user know this is bad input but having a difficult time figuring what the best way to check for it would be.
Edit 1 (Code so far) :
$input=$_GET["expr"];
$nospace_input=str_replace(' ', '', $input);
$input = str_replace('--','+',$input);
$correct_format=preg_match("/^[-.,0-9][-+*.\/, 0-9]+$/",$input);
if ($correct_format==0 && $nospace_input=="") {
//do nothing
}
elseif ($divby_zero==1) {
echo "Can't do div by zero!";
}
elseif($correct_format==1) {
$result = eval('return ' .$input. ';');
echo $input . " = " . $result;
}
else {
echo "Not valid";
}
I'm trying to validate an input for Account number in php form. It should contain 8 numbers and '-' optionally. If there is '-' - it should be ignored.
After pressing the Submit button, the warning message suppose to be displayed above the form in case input is invalid.
Please help.
This is what I got so far, but I'm not sure if this is correct and don't know how to display a warning message above the form.
$acctnum= "$acctnum";
if(empty($acctnum)){
echo "You did not enter an account number, please re-enter"; }
else if(!preg_match("\-^[0-9]{8}", $acctnum)){
echo "Your account number can only contain eight numbers. Please re-enter."; }
Thank you!
You don't appear to be trying. No documentation or tutorial will tell you to make a Regex like that. For starters, where are the delimiters? Why is - escaped when it's outside a character class and therefore has no special meaning? What is that ^ doing there?
This should do it:
$acctnum = str_replace("-","",$acctnum);
if( !preg_match("/^\d{8}$/",$acctnum)) echo "Error...";
Since regex are quite expensive I'd go like that instead:
$acctnum = (int) $acctnum; // this automatically ignore the '-'
if ($acctnum < 0) $acctnum = -$acctnum;
$digits = ($acctnum == 0) ? log10($acctnum) + 1 : 1;
if ($digits === 8) { ... }
Split the task in two. First get rid of the "-" with str_replace and then check for the numbers.
$match = preg_match("/^\d{8}$/", str_replace("_", "", $str));
if ($match > 0) {
// Correct
} else {
// incorrect
}
I am trying to validate a phone number and require it to have 10 digits only no spaces or special characters allowed (example: 0123456789) and the same goes with zip code except 5 digits only (example: 01234).
This is what I have for the phone number field so far.
$phone = stripslashes($_POST['phone']);
if(!$phone || $phone == "Phone Number*")
{
$error .= "Please enter your phone number.<br />";
}
The next if statement should retrieve an error similar to "Please enter a valid phone number. Example: "0123456789".
If you don't want to use regular expressions, take a look at ctype_digit
For example:
if(strlen($phone)==10 && ctype_digit($phone)) {
//valid
} else {
//invalid
}
I can't testify to whether this will be faster or slower than regular expressions, but I would reckon it's probably moot. It's more or less what makes the most sense to you.
You can try regex here:
if(preg_match('/^[0-9]{10}$/', $phone)){
// valid
}else{
// Not valid
}
Something a little like that will ensure only numerical characters and 10 of them. Just change the 10 to 5 for zip code.
One more thing if $_POST['phone'] is not set when you access it you will get a E_NOTICE so just a tip here for you do:
$phone = isset($_POST['phone']) ? stripslashes($_POST['phone']) : null;
if(!$phone) // ERROR
$phone = stripslashes($_POST['phone']);
if(!$phone || $phone == "Phone Number*")
{
$error .= "Please enter your phone number.<br />";
}
if(!preg_match('/^\d{10}$/', $phone)) $error .= "Please enter phone number as ##########.<br />";
And for zip code
if(!preg_match('/^\d{5}$/', $zip)) $error .= "Please enter your zip code as #####.<br />";
Keep in mind that this will not allow foreign zip codes (which may be of different lengths or include letters)
Just some other suggestions too (to prevent unnecessary error messages)
You may want to process your user input such that 123-456-7890 becomes 1234567890 by doing something like
preg_replace('/[^\d]/','',$input)
Maybe do a trim($input) to strip leading/trailing whitespace
Finally, is there any particular reason you are using stripslashes on $_POST['phone']?
If they are all digits like you expect, then this shouldnt be necessary.
If they aren't all digits, then you will throw an error regardless
how about:
function check($number,$length)
{
if(ctype_digit ($number) && strlen($number)==$length)
return true;
else
return false;
}
if(check("1234",4))
echo "ok";
else
echo "Please enter a valid phone number. Example: "0123456789";
Well, this an old post but I will throw in some comments here anyway.
1) you should really not force the user to put in the right numbers, of course your validation on the front end will cover this but never assume it to be case coming into the "backend" .
Consider the following instead of putting the on the user:
// remove chars
$number = preg_replace('/[\D]/', '', $number);
//unit test sanitizer
filter_var($number, FILTER_SANITIZE_NUMBER_INT)
// check number
preg_match('/^[0-9]{10}$/', $zip)
Example : Read in user input if enough digits entered in look up closest matching zipcode etc.. (I actually used this on a site once) Of course setting the frontend to check is useful, but in case that fails .
$number = 'z 02012s';
// remove chars
$number = preg_replace('/[\D]/', '', $number);
//unit test sanitizer
$number = filter_var($number, FILTER_SANITIZE_NUMBER_INT);
// check number
if (preg_match('#^[0-9]{5}$#', $number) === 1) {
//(optional) lookup closest zip using your DB.
$look_zip = $db->getClosestZipMatch($number);
} else {
echo $number . " isn't 5 digits only, do something.";
}
If I have sentences like this:
$msg = "hello how are you?are you fine?thanks.."
and I wish to seperate it into 3 (or whatever number).
So I'm doing this:
$msglen = strlen($msg);
$seperate = ($msglen /3);
$a = 0;
for($i=0;$i<3;$i++)
{
$seperate = substr($msg,$a,$seperate)
$a = $a + $seperate;
}
So the output should be..
hello how are
[a space here->] you?are you [<-a space here]
fine?thanks..
So is it possible to separate at middle of any word instead of having a space in front or end of the separated message?
Such as "thank you" -> "than" and "k you" instead of "thank" " you ".
Because I'm doing a convert function and with a space in front or end it will effect the convertion , and the space is needed for the conversion,so I can't ignore or delete it.
Thanks.
I take it you can't use trim because the message formed by the joined up strings must be unchanged?
That could get complicated. You could make something that tests for a space after the split, and if a space is detected, makes the split one character earlier. Fairly easy, but what if you have two spaces together? Or a single lettered word? You can of course recursively test this way, but then you may end up with split strings of lengths that are very different from each other.
You need to properly define the constraints you want this to function within.
Please state exactly what you want to do - do you want each section to be equal? Is the splitting in between words of a higher priority than this, so that the lengths do not matter much?
EDIT:
Then, if you aren't worried about the length, you could do something like this [starting with Eriks code and proceeding to change the lengths by moving around the spaces:
$msg = "hello how are you?are you fine?thanks..";
$parts = split_without_spaces ($msg, 3);
function split_without_spaces ($msg, $parts) {
$parts = str_split(trim($msg), ceil(strlen($msg)/$parts));
/* Used trim above to make sure that there are no spaces at the start
and end of the message, we can't do anything about those spaces */
// Looping to (count($parts) - 1) becaause the last part will not need manipulation
for ($i = 0; $i < (count($parts) - 1) ; $i++ ) {
$k = $i + 1;
// Checking the last character of the split part and the first of the next part for a space
if (substr($parts[$i], -1) == ' ' || $parts[$k][0] == ' ') {
// If we move characters from the first part to the next:
$num1 = 1;
$len1 = strlen($parts[$i]);
// Searching for the last two consecutive non-space characters
while ($parts[$i][$len1 - $num1] == ' ' || $parts[$i][$len1 - $num1 - 1] == ' ') {
$num1++;
if ($len1 - $num1 - 2 < 0) return false;
}
// If we move characters from the next part to the first:
$num2 = 1;
$len2 = strlen($parts[$k]);
// Searching for the first two consecutive non-space characters
while ($parts[$k][$num2 - 1] == ' ' || $parts[$k][$num2] == ' ') {
$num2++;
if ($num2 >= $len2 - 1) return false;
}
// Compare to see what we can do to move the lowest no of characters
if ($num1 > $num2) {
$parts[$i] .= substr($parts[$k], 0, $num2);
$parts[$k] = substr($parts[$k], -1 * ($len2 - $num2));
}
else {
$parts[$k] = substr($parts[$i], -1 * ($num1)) . $parts[$k];
$parts[$i] = substr($parts[$i], 0, $len1 - $num1);
}
}
}
return ($parts);
}
This takes care of multiple spaces and single lettered characters - however if they exist, the lengths of the parts may be very uneven. It could get messed up in extreme cases - if you have a string made up on mainly spaces, it could return one part as being empty, or return false if it can't manage the split at all. Please test it out thoroughly.
EDIT2:
By the way, it'd be far better for you to change your approach in some way :) I seriously doubt you'd actually have to use a function like this in practice. Well.. I hope you do actually have a solid reason to, it was somewhat fun coming up with it.
If you simply want to eliminate leading and trailing spaces, consider trim to be used on each result of your split.
If you want to split the string into exact thirds it is not known where the cut will be, maybe in a word, maybe between words.
Your code can be simplified to:
$msg = "hello how are you?are you fine?thanks..";
$parts = str_split($msg, ceil(strlen($msg)/3));
Note that ceil() is needed, otherwise you might get 4 elements out because of rounding.
You're probably looking for str_split, chunk_split or wordwrap.