0

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.

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.

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?

Mithrand1r
  • 2,313
  • 9
  • 37
  • 76

4 Answers4

1

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

Arun P Johny
  • 384,651
  • 66
  • 527
  • 531
1

HTML5 has another approach for you:

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

The browser is responsible for the formatting of the date presentation, though.

Alasjo
  • 1,240
  • 8
  • 17
1

use thie regex

/^\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)** 
Rami Jamleh
  • 1,819
  • 1
  • 13
  • 10
0

You can do this with HTML5

see my 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>
Extranion
  • 588
  • 8
  • 25