简体   繁体   English

JavaScript / jQuery输入[type = text]模式

[英]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". 我想让它接受基于像“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". 但我不希望用户输入“X / XXXX / XX”等日期或其他类型的日期,我不希望能够像“// 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. 我不知道如何在这个或jQuery上使用js,因此用户根据模式输入日期而不是以其他方式。

Cheap and easy approach might be just to implement the jQuery UI datepicker control so that you can control the input format through that. 便宜而简单的方法可能只是实现jQuery UI datepicker控件,以便您可以通过它控制输入格式。

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]+)$ : 使用正则表达式^(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. 如果不匹配,它将返回false。 This example uses DD/MM/YYYY. 此示例使用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$ 如果你想要MM / DD / YYYY,请使用以下正则表达式: ^(0?[0-9]|1[0-2])\\/(3[0-1]|[0-2]?[0-9])\\/[1-2][0-9]{3$

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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