0

I want to create a regex expression that I can pass to ng-pattern so that the input can only be valid if the string has only uppercase/lowercase latin letters from a to z, n with tilde, and vowels with acute accents; as well as dot. I came up with what I thought was the solution, but angularjs keeps telling me in the developer tools that my string is not valid when string is:

  • ñ, Ñ
  • á, e, í, ó, ú—also in uppercase
  • a dot followed by a dot followed by a space—not that I am really interested in having that, but I think it should be valid.

This is what I've got : "[A-Za-z\.\s\U+00C1\U+00C9\U+00CD\U+00D1\U+00D3\U+00DA\U+00E1\U+00E9\U+00ED\U+00F1\U+00F3\U+00FA]+"

What am I doing wrong?

P.S. I tried the | operator mentioned in the wiki for the [Jun|Jul|Aug] example, but it acts even weirder.

Bill the Lizard
  • 398,270
  • 210
  • 566
  • 880
Edd
  • 1,948
  • 4
  • 21
  • 29

2 Answers2

1

This regex should work for your needs:

[A-Za-z\.\s\u00C1\u00C9\u00CD\u00D1\u00D3\u00DA\u00E1\u00E9\u00ED\u00F1\u00F3\u00FA]+
StephenRios
  • 2,192
  • 4
  • 26
  • 42
  • This works on all of the characters you provided on this page. Try it out on http://www.regexpal.com/. – StephenRios Mar 15 '17 at 18:19
  • With the plus symbol at the end it is now working. I noticed that you write \u00C1 instead of \U+00C1, could it be that I was using a, reserved if you will, character? – Edd Mar 15 '17 at 18:32
  • the `+` is reserved function character for regex. In this case, it's not necessary. – StephenRios Mar 15 '17 at 19:32
1

You should use a case-insensitive regular expression (the i flag) and escape your special characters with \xHH instead of \u+00HH.

var regex = /^[a-z.\s\xC1\xC9\xCD\xD1\xD3\xDA\xE1\xE9\xED\xF1\xF3\xFA]+$/i

var valid = 'ñ Ñ á e í ó ú'.split(' ')
var invalid = '0 ; Ć'.split(' ')

console.log('Valid:')
valid.forEach(function (e) {
  console.log(regex.test(e)) //=> true
})

console.log('Invalid:')
invalid.forEach(function (e) {
  console.log(regex.test(e)) //=> false
})
.as-console-wrapper { min-height: 100vh; }
gyre
  • 16,369
  • 3
  • 37
  • 47