简体   繁体   中英

JavaScript / jQuery input[type=text] pattern

Ok well, i have an input in a form, which is a date input. I want it to accept characters based on a pattern like "XX/XX/XXXX". Currently it accepts only numbers and "/". But i don't want users to enter dates like "X/XXXX/XX" or some other kind, and i don't want to be able to write it wrong like "//XX/XXX/XXX". I don't know how to use js on this one, or jQuery so the user inputs the date based on the pattern and not in some other way.

Cheap and easy approach might be just to implement the jQuery UI datepicker control so that you can control the input format through that.

It's basically side-stepping the problem but might take the actual problem out of the equation for you.

Use a regex ^(3[0-1]|[0-2]?[0-9])\\/(0?[0-9]|1[0-2])\\/(2[0-9]+)$ :

var date = "20/12/2012";

console.log(isDateOK(date));

function isDateOK(date) {
    return date.match(/^(3[0-1]|[0-2]?[0-9])\/(0?[0-9]|1[0-2])\/([1-2][0-9]{3})$/);
}

It will return false if it doesn't match. This example uses DD/MM/YYYY. if you want MM/DD/YYYY, use the following regex instead: ^(0?[0-9]|1[0-2])\\/(3[0-1]|[0-2]?[0-9])\\/[1-2][0-9]{3$

JSFiddle: http://jsfiddle.net/UBFeN/2/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM