正则表达式在JavaScript中一次又一次失败

时间:2018-08-08 05:46:48

标签: javascript jquery regex

我的名字和姓氏都有一个正则表达式。即使我根据正则表达式给出适当的输入,它也会失败。我尝试更改其他正则表达式,但仍然失败。为了进行测试,我什至只使用了正则表达式,但仍然失败。下面是我正在使用的代码。

<form id="register_form" action="{{url('/register')}}" method="post" accept-charset="UTF-8">
   <div class="col-sm-6">
      <div class="form-group">
            <label for="name">Name</label>
            <input type="text" id="first_name" class="form-control" placeholder="Enter Name" name="first_name">
      </div>
    </div>
</form>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.17.0/jquery.validate.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.17.0/additional-methods.js"></script>

<script type="text/javascript">
    $.validator.addMethod(
        "regex",
        function(value, element, regexp) {
            var re = new RegExp(regexp);
            return this.optional(element) || re.test(value);
        },
        "Number Not valid."
    );

    $("#register_form").validate({
        rules: {
            first_name: {required:true, minlength:2, regex:"^[a-zA-Z]+((\\s|\\-)[a-zA-Z]+)?$"},
        },
        messages:   {
            first_name:{required:'First name is required',minlength:'First name should contain atleast two alphabets',regex:'Only alphabets allowed and it should not start with space.'},
        }
    );
</script>

我失败的输入是Raj Shah,这应该工作得很好。我检查了重复的输入ID,但没有。我在在线测试仪上检查了正则表达式,它工作正常。

2 个答案:

答案 0 :(得分:0)

虽然您的正则表达式模式似乎可以正常工作,但问题可能出在正则表达式模式的传递方式上,它可能已经经过了转义过程,在您的反斜杠字符之前通过添加另一个反斜杠来再次对其进行转义。

如果可以看到至少3个反斜杠而不是2个,则可以尝试将0字符串记录到控制台。

您还应该尝试使用const {google} = require('googleapis'); const path = require('path'); const util = require('util') async function runSample () { // Create a new JWT client using the key file downloaded from the Google Developer Console const authClient = await google.auth.getClient({ keyFile: path.join(__dirname, 'jwt.keys.json'), scopes: 'https://www.googleapis.com/auth/pubsub' }); // Obtain a new pubsub client, making sure you pass along the authClient const pb = google.pubsub( { version:'v1', auth: authClient }); //make a request to list subscriptions //the returned object is a axios response object const res = await pb.projects.subscriptions.list( { project: 'projects/my-project' }); //return response data return res.data; } runSample().then(res =>{ console.log(util.inspect(res, false, null)) }).catch(console.error); 而不是regex,以使反斜杠字符不会插在您的字符串中。

single quotes

代替

double quotes

您还可以尝试在正则表达式中添加'^[a-zA-Z]+((\\s|\\-)[a-zA-Z]+)?$' 反斜杠:

"^[a-zA-Z]+((\\s|\\-)[a-zA-Z]+)?$"

答案 1 :(得分:0)

尽管您的正则表达式没有问题并且您的输入应该通过,但您似乎在验证器逻辑方面存在问题。我不确定这是否会有所帮助,但是我建议将regex参数和regexp参数命名为相同,以防万一,然后在外面编译regexp验证方法。

$.validator.addMethod(
  "regex",
  function(value, element, regex) {
    return this.optional(element) || regex.test(value);
  },
    "Number Not valid."
  );
$("#register_form").validate({
  rules:
    {
      first_name: {
        required:true,
        minlength:2,
        regex:/^\p{L}+((\s|-)\p{L}+)?$/u},
      },
      messages: {
        first_name:{
          required:'First name is required',
          minlength:'First name should contain at least two letters',
          regex:'Only letters allowed and it should not start with space.'},
});