I have a form, where the user must fill in his id card number. Id number of cards has a length of 16 character. I want to check whether the string entered is correct only a number with a length of 16 characters?
i have this code:
<?php
$nik=1234567891234567;
if(!preg_match('/^[1-9][0-9]{16}$/', $nik)){
echo 'nooooo';
exit;
}else{
echo 'yesss';
exit;
}
?>
the result will echoed nooooo, is there anything wrong with its regex?
What you want is something like this:
<?php
$nik=1234567891234567;
var_dump($nik);
if(preg_match('/^[1-9]\d{15}$/', $nik)){
echo "Contains only numbers";
exit;
}else{
echo "Contains non-numeric characters";
exit;
}
This will match a string with exactly 16 characters; the first can be 1-9
, but the rest can be any digit. Your regex, /^[1-9][0-9]{16}$/
, matches a character in the range 1-9
, then 16 characters in the range 0-9
, for a total of 17 characters.
Also, your code has a logical flaw: your number is larger than the maximum integer value on a 32-bit system, as stated in the documentation. The largest value on any system can be determined by checking the constant PHP_INT_MAX
. For a 32-bit system, this is 2147483647
. That has fewer than 16 characters, so your code will not work reliably on a 32-bit system.
Also, your post said you're getting this info from a user via a form. In that case, you will be receiving a string, not an integer. For example, if your field is named nik
, then you would access the info with $_POST['nik']
(for a POST form) or $_GET['nik']
(for a GET form). Then, just use it as a string; it's not really a number, anyway.
You're checking for a 16-character number. This sounds like something involving credit cards. If you are doing credit card processing, you should know that there are major security implications and compliance issues related to processing cards on your server. I can't give you legal advice, and how to properly process a credit card is much too broad a topic for this site. But I will say this: if this is credit card data, you do not want to do it this way unless you have a very large budget for compliance issues, auditing, and the like. You should look into using PayPal, Stripe, or a similar vendor to handle this.