Reputation: 35
I am trying to add a regular expression in my AngularJS controller that validates the four following conditions in a text input box:
A) name (space) name
, B) name,(comma) name
, C) 123456789
(max of 9 digits) D) 123-45-6789
I created the following regex:
1) validation: /^[a-zA-Z0-9 ,\-]+[(?<=\d\s]([a-zA-Z0-9]+\s)*[a-zA-Z0-9]+$ /
,
This is close to what I want with the exception of formatting the last four digits and limiting digits to a max of nine characters.
I also tried combining the following regex per my research to no avail:
2) validation: /^([0-9]{8,9})$/ + /^([A-z'\/-])+[\s]+([A-z'\/-])+$/ + /^([A-z'\/-])+[\s]*[\,]{1}[\s]*([A-z-\/'])+$/ + /^\d{3}-\d{2}-\d{4}$/
,
3) validation: /^([0-9]{8,9})$/ | /^([A-z'\/-])+[\s]+([A-z'\/-])+$/ | /^([A-z'\/-])+[\s]*[\,]{1}[\s]*([A-z-\/'])+$/ | /^\d{3}-\d{2}-\d{4}$/
,
4) validation: new RegExp('(' + /^([0-9]{8,9})$/ + ") | (" + /^([A-z'\/-])+[\s]+([A-z'\/-])+$/ + ") | (" + /^([A-z'\/-])+[\s]*[\,]{1}[\s]*([A-z-\/'])+$/ + ") | (" + /^\d{3}-\d{2}-\d{4}$/ + ')')
,
I have three questions:
Is it possible to create one regex that validates these four conditions?
Am I not combining these correct?
Or should I abandon this regex mission and just create a separate function to perform my validation?
Upvotes: 1
Views: 349
Reputation: 1865
This should work for you: ^([a-zA-Z]+(?:-\/)?[,\/]?\s+[a-zA-Z]+(?:-\/)?|\d{1,9}|\d{3}-\d{2}-\d{4})$
const validate = input => /^^([a-zA-Z]+(?:-\/)?[,\/]?\s+[a-zA-Z]+(?:-\/)?|\d{1,9}|\d{3}-\d{2}-\d{4})$/.test(input)
const testData = ["123", "name space", "John Doe", "John/ Doe", "Doe, John", "John", "name, ", "John Doe", "John-/ Doe", "John-/, Doe-/", "sdf", "123-45-6789", "1234567890" ,"name , surname"]
for (const input of testData){
console.log(`${input} ${validate(input)}`)
}
Upvotes: 1
Reputation: 43199
You could go for
^(?:(?:[a-z]+,?[ ]+[a-z]+)|(?:\d{3}-\d{2}-\d{4})|(?:\d+))$
^ # match beginning of the line
(?: # non-capturing parenthesis
(?:[a-z]+,?[ ]+[a-z]+) # a-z then comma (optional) space then a-z again
| # or
(?:\d{3}-\d{2}-\d{4}) # the number format with dashes
| # or
(?:\d+) # only numbers
)
$ # match the end of the line
Upvotes: 1