0

I am using javascript regex for validating user entered date in format mm/yyyy. I have made regex for this and its working fine, but when I enter ab/abcd its still validating it.

This is my JS and HTML code

function validate() {
    var name = document.getElementById("name").value;
    var pattern = /\d|\/|\d{4}/;        
    if (pattern.test(name)) {
        alert(name +" has alphanumeric value");
        return true;
    } else {
        alert("Name is not valid.Please input alphanumeric value!");
        return false;
    }
}
Date: <input type="text" name="name" id="name" />
<input type="submit" value="Check" onclick="validate();"/>

How can I validate the entered date in mm/yyy format, I am using Jquery DatePicker which allows to select date in this format, and the datepicker also allows manual input. like this Date Picker Is there any alternate suggestion for this?

1
  • You want to allow the data which is in the mm/dddd format? Commented Apr 21, 2014 at 6:52

1 Answer 1

1

Updated:

Try the pattern below instead:

var pattern = /^\d{2}\/\d{4}$/;    

See the working code at:

JSFiddle

Another fiddle for extracting the month:

JsFiddle2

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

6 Comments

Thanks its working, Can I give Number Range here? like month can be between 1-12?
Not with the regex, I believe. You might want to look at some other validation methods out there.
ok thanks, Just one more question, with this pattern if user enters 1/2014 it will not validate the month, it will only validate if he enter 01/2014, what should I do in this case
You may extract the first number before "/" and evaluate it yourself to ensure that it's between 1 and 12.
var pattern = /^\d\d?\/\d{4}$/;
|

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.