2

How can I validate a form field upon submission before sending a request to the server that the serial number has this exact format :

 <input type="text" id="serial" placeholder="123AB-BCXH3-778F2-90763">

(20 Characters, seperated by - for every 5 characters )

Thanks

Answer

Previous title was : Javascript check string format

My question was how to validate with Javascript but Joe below gave a good example using regex expressions, I have never used Regex but this what i learned today :

^\w{5}-\w{5}-\w{5}-\w{5}$ Where my Serial format is 5 Characters followed by "-"

  • \w => is any word Character a-z, A-Z, 0-9
  • {5} => Count 5 Characters
  • \- => backslash causes the metacharacter to be treated as a character, here "-"
  • $ => end of string
  • ^ => Starting position
8
  • No need for JavaScript or jQuery, you can do this with HTML5 form validation in modern browsers :) Commented Mar 14, 2014 at 15:30
  • really? any link I can check out? Commented Mar 14, 2014 at 15:31
  • 4
    Sure, here's the first google result, basically you can specify a pattern attribute on input elements Commented Mar 14, 2014 at 15:31
  • great benjamin! Will definitely do it with HTML Commented Mar 14, 2014 at 15:33
  • 1
    When you do, please consider posting your solution as an answer so future visitors will know how to solve it. Good luck! Commented Mar 14, 2014 at 15:34

1 Answer 1

2

Here is a functional fiddle

<form>
    <input type="pid"  id="pid" maxlength="23" pattern="^\w{5}\-\w{5}\-\w{5}\-\w{5}$" required value="123AB-BCXH3-778F2-90763" size="35"/>

    <input type="submit" value="Submit" />
</form>
Sign up to request clarification or add additional context in comments.

2 Comments

The size property was just to be able to see the whole code.
Thanks Joe, very helpful approach. Answer added above.

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.