首页 > 解决方案 > 将输入字段与 PHP 中的 CNIC 编号匹配?

问题描述

我想将提到的正则表达式与 CNIC 编号输入字段匹配,但我不知道如何?这是我的正则表达式和代码。任何帮助将不胜感激。

  1. 如果用户匹配了某些东西并且它匹配了模式,那么它将在下面的范围中显示“有效”。
  2. 如果不匹配,则会显示“无效”。

我想要的结果模式是 12345-1234567-1

<?php

    // NIC Validation
    // valid ouput sample 12345-1234567-1
   $nicRegex = '^([0-9]{5})[-]([0-9]{7})[-]([0-9]{1})$';


  if (empty($_GET["nic"])) {
            $nicError = "Please enter the nic number";
          }
  // if nic does match it should display valid else invalid       

?>
<!DOCTYPE html>
<html>
<head>
    <title>Form Validation Example</title>
    <style>
        span{
            color:red;
        }
    </style>
</head>
<body>

 
  <hr width="100%">

<form action="" method="GET" id="signup_form">
    
    <p>
        <label>CNIC validtion using format (12345-1234567-1) <input type="text" name="nic" autocomplete="off" autofocus tabindex="1"> 
            </label>
    </p><span> <?php echo $nicError; ?></span>
    

        <input type="submit" name="submit" value="Submit Form">
    </p>

</form>


</body>
</html>

标签: phphtmlregexforms

解决方案


我也遇到了这个问题,所以我对这个问题进行了很多搜索,最后我得到了一个可行的解决方案:

form cnic input field
 

        $cnic = $_POST['cnic'];
    // patter for cnic is:
    
        $cnic_pattern = '/[0-9]{5}[-][0-9]{7}[-][0-9]{1}/';

    check weather the pattern is matched to the cnic field 
    
        if(preg_match_all[$pattern, $cnic]{
        echo "Yes! This is true";
        }else{
        echo "Oh! false;
        }

推荐阅读