2

I'm trying to use jquery validator plugin to test a regEx and display an error message when the regex is not matched. Take a look at the code that I have written so far.

<form name="sampleForm" id="sampleForm" class="col-xs-10 col-xs-offset-1" style="margin-top:10px;">
    <input type="text" id="phoneNumber" name="phoneNumber" class="form-control" required/><br/>
    <input type="text" class="form-control" id="name" name="name"/>
    <button type="submit" class="btn btn-success col-xs-4 col-xs-offset-4" style="margin-top:10px;">Submit</button>
</form>   

Also take a look at the js code that I have written below :

<script>
  $().ready(function() {
    $('#sampleForm').validate({
      rules: {
        phoneNumber: {
          required: true,
          nameTest: true
        }
      },
      messages: {
        phoneNumber: {
          required: "Please enter anything"
        }
      }
    });
  });
  jQuery.validator.addMethod("nameTest", function(value, element) {
    return /^[a-Z]$/.test(value);
  }, "success, it's working");
</script>

I just used a simple regEx to allow only a-z alphabets with /^[a-Z]$/.

I don't know why but I'm getting :

Invalid regular expression: /^[a-Z]$/: Range out of order in character class

Please help, thanks in advance :)

Sparky
  • 98,165
  • 25
  • 199
  • 285
Harish
  • 1,193
  • 6
  • 22
  • 45

1 Answers1

4

The error is because a (97) is after Z (90) in the ASCII encoding sequence - so the range is out of order:

console.log('a'.charCodeAt(0));
console.log('Z'.charCodeAt(0));

So this would be valid (but not intuitive):

/^[Z-a]$/

You should use this regex to match letters A to Z for both upper and lower case:

/^[A-Za-z]$/
Robin Mackenzie
  • 18,801
  • 7
  • 38
  • 56