0

I have been using regex pattern with 'message-when-pattern-mismatch' error message for some lightning input fields in LWC component.

regex1 is like : pattern="^[A-Za-z-.' ]*" [it should allow only alphabets(lowercase/uppercase) and the following special characters (-), (.) and (‘).]

regex2 is like : pattern="^(?(\d{3}))?[ .-]?(\d{3})[ .-]?(\d{4})( ?(ext.? ?|x)(\d*))?$" [phone field with format (111) 111-1111 and should allow 10 digits only]

The Problem is, instead of showing error message in the UI, its showing pattern error in the console. following are the pattern errors,

regex1 pattern error: Pattern attribute value ^[A-Za-z-.' ]* is not a valid regular expression: Uncaught SyntaxError: Invalid regular expression: /^[A-Za-z-.' ]*/v: Invalid character class

regex2 pattern error: Pattern attribute value ^(?(\d{3}))?[ .-]?(\d{3})[ .-]?(\d{4})( ?(ext.? ?|x)(\d*))?$ is not a valid regular expression: Uncaught SyntaxError: Invalid regular expression: /^(?(\d{3}))?[ .-]?(\d{3})[ .-]?(\d{4})( ?(ext.? ?|x)(\d*))?$/v: Invalid character in character class

Does anyone have any idea why it's not working? What needs to be update in these patterns? Thanks.

2
  • 1
    Move the '-' representing hyphen to the start or end of the character choices. Right now it is being treated as a range specifier, which is breaking it.
    – Phil W
    Dec 16, 2023 at 17:13
  • Yes, hyphen is a problem, but I think for both cases a backslash in front of all '-' representing hyphens is better. I don't get why you don't escape the brackets that are meant to represent themselves in the second expression - try '\' there too, start with something like ^\(?(\d{3})\)?... Dec 16, 2023 at 18:03

1 Answer 1

-1

whatever you provided patterns are not support in LWC that's why it was throwing console errors. I modified patterns like below

Old Pattern : ^[A-Za-z-.' ]*

New Pattern : ^[A-Za-z\-.']

old Pattern : ^(?(\d{3}))?[ .-]?(\d{3})[ .-]?(\d{4})( ?(ext.? ?|x)(\d*))?$

New Pattern : (\([0-9]{3})\)+[\-.]+([0-9]{3})+[\-.]+([0-9]{4})

Try these new patterns it will work for you

2
  • This sounds incorrect to me, and doesn't agree with the comments by established users. Getting rid of the kleene star means your first suggestion would only match a single character. If you can point to official documentation to support your answer, you should. Otherwise, this is not an answer people should use.
    – Derek F
    Dec 18, 2023 at 15:32
  • @DerekF I tested these two regex patterns It was working for me. I just given solution for this use case only. I don't have official support document for this one. Dec 19, 2023 at 4:13

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .