简体   繁体   English

html&js文本字段数据(DD-MM-YYYY)验证

[英]html & js text field data (DD-MM-YYYY) validation

In my form I have a text field in which user type date. 在我的表单中,我有一个用户输入日期的文本字段。 Good habit tells me to not let user to put anything other then dgit and '-' symbol in the field. 良好的习惯告诉我,不要让用户在字段中输入除dgit和'-'符号以外的任何内容。

However i have a bit problem with implementing such feature. 但是我在实现这样的功能时有点问题。 So far I Have a field which accept only digits. 到目前为止,我有一个仅接受数字的字段。 If user try to put in field letter, this letter is being removed. 如果用户尝试输入字段字母,该字母将被删除。 But the point is to create (DD-MM-YYYY) format so field have to accept '-' symbol. 但是关键是要创建(DD-MM-YYYY)格式,因此字段必须接受'-'符号。

Here is my code: 这是我的代码:

<input type="text" name="test3" placeholder='DD-MM-YYYY' onkeyup="if (/\D/g.test(this.value)) this.value = this.value.replace(/\D/g,'')"/>

i tried put |\\- into regex but with no success. 我试图将|\\-放入正则表达式中,但没有成功。 Can anyone point me where I am doing mistake? 谁能指出我在哪里做错了?

You can try something like 您可以尝试类似

<input type="text" name="test3" placeholder='DD-MM-YYYY' onkeyup="if (/[^\d-]/g.test(this.value)) this.value = this.value.replace(/[^\d-]/g,'')" onchange="validate(this)"/>

function validate(el){
    var regex = /^(0?[1-9]|[12][0-9]|3[01])-(0?[1-9]|1[012])-\d{4}$/;
    if(!regex.test(el.value)){
        alert('invalid date');
        el.value = '';
    }
}

Demo: Fiddle 演示: 小提琴

HTML5 has another approach for you: HTML5为您提供了另一种方法:

<input type="date" name="test3">

The browser is responsible for the formatting of the date presentation, though. 但是,浏览器负责日期显示的格式设置。

use thie regex 使用正则表达式

/^\\d{4}-\\d{2}-\\d{2}$|[^\\d-]|-\\d{2}-\\d*-/ / ^ \\ d {4}-\\ d {2}-\\ d {2} $ | [^ \\ d-] |-\\ d {2}-\\ d *-/

you can also 你也可以

 **/^\d{4}-\d{2}-\d{2}$|[^\d-]|-\d{2}-\d*-/.test(input.value)** 

You can do this with HTML5 您可以使用HTML5做到这一点

see my jsfidle: http://jsfiddle.net/H7tMZ/2/ 看到我的jsfidle: http : //jsfiddle.net/H7tMZ/2/

<form>
    <input type="text" name="date" pattern="\d{1,2}-\d{1,2}-\d{4}" placeholder="dd-mm-jjjj"/>
    <button type="submit"/>
</form>

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

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