0

I want to validate hostnames (ie x.y.z format). Currently I'm using the regular expression below, but it is not working.

It accepts x.y.z.a etc. I want to restrict it to only accept x.y.z. Does anyone know how I can fix it?

/^([a-z0-9]+(-[a-z0-9]+)*\.)+([a-z]{2,12})$/i

2 Answers 2

1

Just replace the + modifier with {1,2}:

/^([a-z0-9]+(-[a-z0-9]+)*\.){1,2}([a-z]{2,12})$/i

And, if you don't need the capture groups:

/^(?:[a-z0-9]+(?:-[a-z0-9]+)*\.){1,2}[a-z]{2,12}$/i

If you want exactly 3 parts (x.y.z), use {2} instead of {1,2}

/^(?:[a-z0-9]+(?:-[a-z0-9]+)*\.){2}[a-z]{2,12}$/i
Sign up to request clarification or add additional context in comments.

Comments

0

This will do the job. Above regex will match only x.y.z format

^([a-z0-9]\.){2}[a-z0-9]$

Two times x. format with a x at the end.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.