georgesamper
georgesamper

Reputation: 5169

RegEx only one dot inside string not at beginning or end

How can I write a regular expression in javascript that only allows users to write this:

abc.def, abc-def or abc

So basically match a pattern that only contains letters (only lowercase [a-z]) and a . or -. But does not match - or . at the beginning or end of string or multiple times(only one . or - per string)

So not allowing them to do:

..... abc...abc abc.abc.... abc----.... ...abc.abc .abc -abc etc.

Upvotes: 3

Views: 7572

Answers (1)

Ωmega
Ωmega

Reputation: 43673

Regex would be: /^[a-z]+([\.\-]?[a-z]+)?$/

JavaScript:

var text = 'abc.def';
var pattern = /^[a-z]+([\.\-]?[a-z]+)?$/;
if (text.match(pattern)) {
  print("YES!");
} else {
  print("NO!");
}

See and test the code here.

Upvotes: 10

Related Questions