1

I am working with a C++ project on an ESP8266 controller and displaying a captive portal. The portal itself is created by an external library and somewhat limited with regard to the portal page generated. I only have the ability to add attributes to the form field which the code creates. In other words, I have an input field that is generated on the page/portal, and I can modify it with attributes such as pattern, min, max, etc.

I want to allow the user to enter a hostname, and to keep it exceedingly simple and compatible with potentially dated technology, I want to enforce that the hostname begins with an alpha character, must be between 3 and 24 characters, may contain alphanumeric characters and/or a hyphen, and must not end with a hyphen.

Clearly, the pattern attribute is just the thing here. The problem is I have failed so far to come up with a good working example. In my example below, it enforces a beginning alpha, and if I enter something it enforces a minimum of 3 characters, but if I enter nothing it accepts it as valid. I've also not quite figured out how to limit the last character to alphanumeric.

<input type="text" name="hostname"
    pattern="^[a-zA-Z][a-zA-Z0-9-]{2,24}$"
    title="Enter a hostname, 3-14 characters, beginning
    with a letter and containing only alphanumeric
    characters and/or a hyphen.  It must end with an
    alphanumeric."
>

So a few tests which I would like to work correctly are:

  • a-b (good)
  • a12 (good)
  • ab- (bad)
  • ab (bad)
  • 1ab (bad)

I'm a little incredulous that my Google-fu has failed me here.

1 Answer 1

1

When you don't input anything, no validation occurs because the input is not specified as required, so add the required attribute.

Also, since you want the field to have 3-24 characters, the repetition after the first character should be {1,22}, and the last token should be [a-zA-Z\d] to ensure that the last character isn't a hyphen:

^[a-zA-Z][a-zA-Z\d-]{1,22}[a-zA-Z\d]$

<form><input type="text" name="hostname" required pattern="^[a-zA-Z][a-zA-Z\d-]{1,22}[a-zA-Z\d]$" title="Enter a hostname, 3-14 characters, beginning
    with a letter and containing only alphanumeric
    characters and/or a hyphen.  It must end with an
    alphanumeric.">
    <button>click</button>
</form>

Sign up to request clarification or add additional context in comments.

1 Comment

Fantastic, thank you! I was close but I wasn't gonna get that without a nudge.

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.