【问题标题】:Match input field with CNIC Number in PHP?将输入字段与 PHP 中的 CNIC 编号匹配?
【发布时间】:2021-05-01 12:31:04
【问题描述】:

我想将提到的正则表达式与 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>

【问题讨论】:

标签: php html regex forms


【解决方案1】:
^[0-9]{5}-[0-9]{7}-[0-9]$

你不需要把 1 放在它不需要的末尾,你也不需要 - 在大括号中

【讨论】:

  • 亲爱的,我的问题不是那个,而是我的问题是如何将该正则表达式与输入字段匹配。
【解决方案2】:

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

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;
        }

【讨论】:

  • 虽然这可能会回答这个问题,但最好还包括解释它解决问题的原因(它是如何工作的),以便任何未来的读者都可以从中学习。
猜你喜欢
  • 2014-09-14
  • 2015-10-24
  • 2020-04-30
  • 2015-01-08
  • 1970-01-01
  • 2023-04-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多