1

I am using a textbox on my page which is used to enter year in yyyy-yyyy format.

Can you tell how can i validate textbox in this format through javascript??

Thanks in advance...

5
  • Do you mean a range of years? eg (between) 1980-1993 Commented Jun 3, 2011 at 8:21
  • @minikomi: not between 1980-1993..even i want to enter year like 1980-1999 Commented Jun 3, 2011 at 8:23
  • What @minikomi means is, whether you want to validate the format only (i.e. 4 digits dash 4 digits) or also the range of the years (e.g. the users are not allowed to enter a start date that is before 1975). We have to know that to be able to give you a correct answer. Commented Jun 3, 2011 at 8:24
  • @ Felix Kling: yes, i want to validate the format only (i.e. 4 digits dash 4 digits). Commented Jun 3, 2011 at 8:27
  • 1
    In which case, Merjin's answer should be fine... Be careful what you accept and how you want to use it though! Commented Jun 3, 2011 at 9:31

2 Answers 2

4

You can match it with a regular expression:

var pattern = /\d{4}-\d{4}/;

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

3 Comments

Hmm.. but does year 0000 make sense? How about 9999? What to do in the case 2831-0134...
@minikomi - Merjin's RegExp is what the OP asked for. Of course it may not be what they want. :-)
Yep, just saw the new comment.. sorry!
2

If you are not using any javascript library (like jQuery, etc), Javascript Regular Expressions could be used for validating the input.

2 Comments

Why would jQuery help or be an alternative to a regular expression?
It's not an alternative. But some of jQuery plugins could complement and simplify the pure regular expression approach.

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.