jQuery验证中的正则表达式 - 要求一个5位数字和1个字母(字母不区分大小写)

3

我想制作一个带有一些验证的表单,但遇到了一个问题,就是注册号码的验证。每个用户已经属于一个协会,所以当他们与我们联系时,我们需要通过检查数据库中的号码来验证是否为其本人。我需要的帮助是关于注册号码正则表达式的部分。

目标是让他们提交一个由5位数字和1个字母组成的号码。字母不区分大小写。到目前为止,我尝试了以下内容:

^(\d{5})([A-Z]{1})$

任何类似12345A的数字都可以接受。

这个验证似乎有点过度,但我们的用户经常插入错误信息,并且不能立即回复电子邮件,因此他们可以提交正确的详细信息,而不必追着他们要正确的信息。

感谢任何帮助或指出错误。

contact.js

$(function() {
  // Validate the contact form
  $('#contactform').validate({
    // Specify what the errors should look like
    // when they are dynamically added to the form
    errorElement: "label",
    wrapper: "td",
    errorPlacement: function(error, element) {
      error.insertBefore(element.parent().parent());
      error.wrap("<tr class='error'></tr>");
      $("<td></td>").insertBefore(error);
    },

    // Add requirements to each of the fields
    rules: {
      name: {
        required: true,
        minlength: 2
      },
      email: {
        required: true,
        email: true
      },
      RegNo: {
        required: true,
        minlength: 6
      },
      tuname: {
        required: true,
        minlength: 1
      },
      dob: {
        required: true,
        minlength: 10
      }
    },

    // Specify what error messages to display
    // when the user does something horrid
    messages: {
      name: {
        required: "Please enter your name.",
        minlength: jQuery.format("At least {0} characters required.")
      },
      email: {
        required: "Please enter your email.",
        email: "Please enter a valid email."
      },
      RegNo: {
        required: "Please enter your Reg No. (eg. 12345A)",
        minlength: jQuery.format("At least {0} characters required. eg. 12345A")
      },
      tuname: {
        required: "Please enter your Twitter Username.",
        minlength: jQuery.format("At least {0} characters required.")
      },
      dob: {
        required: "Please enter a DOB.",
        dob: jQuery.format("At least {0} characters required.")
      }
    },

    // Use Ajax to send everything to processForm.php
    submitHandler: function(form) {
      $("#send").attr("value", "Sending...");
      $(form).ajaxSubmit({
        success: function(responseText, statusText, xhr, $form) {
          $(form).slideUp("fast");
          $("#response").html(responseText).hide().slideDown("fast");
        }
      });
      return false;
    }
  });
});

strong text
<?php

// Clean up the input values
foreach($_POST as $key => $value) {
 if(ini_get('magic_quotes_gpc'))
  $_POST[$key] = stripslashes($_POST[$key]);
 
 $_POST[$key] = htmlspecialchars(strip_tags($_POST[$key]));
}

// Assign the input values to variables for easy reference
$name = $_POST["name"];
$email = $_POST["email"];
$RegNo = $_POST["RegNo"];
$tuname = $_POST["tuname"];
$dob = $_POST["DOB"];

// Test input values for errors
$errors = array();
if(strlen($name) < 2) {
 if(!$name) {
  $errors[] = "You must enter a name.";
 } else {
  $errors[] = "Name must be at least 2 characters.";
 }
}
if(!$email) {
 $errors[] = "You must enter an email.";
} else if(!validEmail($email)) {
 $errors[] = "You must enter a valid email.";
}
if(strlen($RegNo) < 6) {
   if(!$RegNo) {
      $errors[] = "You must enter a Reg Number. (e.g. 12345A)";
   } else {
      $errors[] = "Name must be at least 6 characters. (e.g. 12345A)";
   }
}
if(strlen($tuname) < 2) {
   if(!$tuname) {
      $errors[] = "You must enter your twitter username.";
   } else {
      $errors[] = "Username cannot be blank.";
   }
}
if(strlen($DOB) < 10) {
 if(!$DOB) {
  $errors[] = "You must enter a D.O.B.";
 } else {
  $errors[] = "D.O.B. must be at least 10 characters.";
 }
}

if($errors) {
 // Output errors and die with a failure message
 $errortext = "";
 foreach($errors as $error) {
  $errortext .= "<li>".$error."</li>";
 }
 die("<span class='failure'>The following errors occured:<ul>". $errortext ."</ul></span>");
}

// Send the email
$to = "email@domain.com";
$subject = "email subject";
$message = "$name, $RegNo, $tuname, $dob";
$headers = "From: $email";

mail($to, $subject, $message, $headers);

// Die with a success message
die("<span class='success'>Success! Your message has been sent.</span>");

// A function that checks to see if
// an email is valid
function ValidatePPS($RegNo) {
var formatRegex = /^(\d{7})([A-Z]{1,2})$/i;

if (!formatRegex.test($RegNo)) {
return "The format of the provided PPSN is invalid"; }
}

function validEmail($email)
{
   $isValid = true;
   $atIndex = strrpos($email, "@");
   if (is_bool($atIndex) && !$atIndex)
   {
      $isValid = false;
   }
   else
   {
      $domain = substr($email, $atIndex+1);
      $local = substr($email, 0, $atIndex);
      $localLen = strlen($local);
      $domainLen = strlen($domain);
      if ($localLen < 1 || $localLen > 64)
      {
         // local part length exceeded
         $isValid = false;
      }
      else if ($domainLen < 1 || $domainLen > 255)
      {
         // domain part length exceeded
         $isValid = false;
      }
      else if ($local[0] == '.' || $local[$localLen-1] == '.')
      {
         // local part starts or ends with '.'
         $isValid = false;
      }
      else if (preg_match('/\\.\\./', $local))
      {
         // local part has two consecutive dots
         $isValid = false;
      }
      else if (!preg_match('/^[A-Za-z0-9\\-\\.]+$/', $domain))
      {
         // character not valid in domain part
         $isValid = false;
      }
      else if (preg_match('/\\.\\./', $domain))
      {
         // domain part has two consecutive dots
         $isValid = false;
      }
      else if(!preg_match('/^(\\\\.|[A-Za-z0-9!#%&`_=\\/$\'*+?^{}|~.-])+$/',
                 str_replace("\\\\","",$local)))
      {
         // character not valid in local part unless 
         // local part is quoted
         if (!preg_match('/^"(\\\\"|[^"])+"$/',
             str_replace("\\\\","",$local)))
         {
            $isValid = false;
         }
      }
      if ($isValid && !(checkdnsrr($domain,"MX") || checkdnsrr($domain,"A")))
      {
         // domain not found in DNS
         $isValid = false;
      }
   }
   return $isValid;
}

function validateDate($dob)
{
    $d = DateTime::createFromFormat('d-m-Y', $dob);
    return $d && $d->format('d-m-Y') === $dob;
}

?>

**index.html**
<div id="form-group" align="center">
  <form id="contactform" action="processForm.php" method="post">
    <table>
      <br>
      <tr>
        <td>
          <p>
            <label for="name">Full Name:</label>
        </td>
        <td>
          <input type="text" id="name" name="name" class="form-control" />
          </p>
        </td>
      </tr>
      <tr>
        <td>
          <p>
            <label for="email">Email Address:</label>
        </td>
        <td>
          <input type="email" id="email" name="email" class="form-control" />
          </p>
        </td>
      </tr>
      <tr>
        <td>
          <p>
            <label for="RegNo">Garda Reg No:</label>
        </td>
        <td>
          <input type="text" id="RegNo" name="RegNo" class="form-control"></input>
          </p>
        </td>
      </tr>
      <tr>
        <td>
          <p>
            <label for="tuname">Twitter Username:</label>
        </td>
        <td>
          <input type="text" id="tuname" name="tuname" class="form-control"></input>
          </p>
        </td>
      </tr>
      <tr>
        <td>
          <p>
            <label for="dob">D.O.B:</label>
        </td>
        <td>
          <input type="date" id="dob" name="dob" class="form-control" placeholder="00/00/00"></input>
          </p>
        </td>
      </tr>
      <tr>
        <td></td>
        <td>
          <p>
            <input type="submit" value="Send!" id="send" type="button" class="btn btn-primary" />
          </p>
        </td>
      </tr>
    </table>
  </form>
  <div id="response"></div>
</div>


1
这里有什么不起作用? - Wiktor Stribiżew
1
我们需要使用addMethod API。 这个链接会对你有所帮助 https://dev59.com/E2Yr5IYBdhLWcg3wTYgQ - Bkjain655
@Bkjain655,你说得对。我添加了一个addMethod并给它一个正则表达式。然后在该字段的规则中设置了该正则表达式。感谢您的帮助。 - gwolfe
1个回答

1
在你的正则表达式中,{1} 是不必要的,因为 [A-Z] 已经强制只有一个字符。该表达式可以重写为 ^(\d{5})([A-Z])$
否则,你的表达式将匹配任何由5个数字后跟单个字母组成的字符串。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接