• Status: Solved
  • Priority: High
  • Security: Public
  • Views: 62
  • Last Modified:

Javascript date mask

Hi E's,
I have a date mask, but not work perfect.
The code is this one:
<input id="lancamento" value="<? echo $linha[data2]; ?>" type="text" name="date" placeholder="yyyy-mm-dd" onkeyup="var v = this.value; if (v.match(/^\d{4}$/) !== null){this.value = v + '-';} else if (v.match(/^\d{4}\/\d{2}$/) !== null) {this.value = v + '-';}" maxlength="10">

Open in new window

The mask as been create for format data: yyyy-mm-dd.
The problem is, the last "-" not appear, and when I write the date occurs something like this: 2018-0422, when the correct is 2018-04-22!

What is wrong in my code?

The best regards, JC
Pedro Chagas
Pedro Chagas
1 Solution
Leonidas DosasCommented:
What is the echo value in the input?
Pedro ChagasWebmasterAuthor Commented:
Hi @Leonidas,
You can see the echo in attach image.
Can you please help me?

Leonidas DosasCommented:
Check this function
function a(arg){ 
  var y,x,z;  
  return x;

Open in new window

Cloud Class® Course: Amazon Web Services - Basic

Are you thinking about creating an Amazon Web Services account for your business? Not sure where to start? In this course you’ll get an overview of the history of AWS and take a tour of their user interface.

Pedro ChagasWebmasterAuthor Commented:
Hello @Dosas,
Can you please show me how to relate your solution to the input?

Thank you.
David S.Commented:
That second condition will never match, since it's checking for a different separator.

Why are you using inline events anyway?

You can simplify the code by using one regular expression to check for both conditions. Also, when you simply want to know if the expression matches or not, it's more efficient to use RegExp.test() instead of String.match().
var v = this.value; if (/^\d{4}(-\d{2})?$/.test(v)){this.value = v + '-';}

Open in new window

Julian HansenCommented:
Advice - don't put your code inline. Create a function for it and call that - it will be much easier to debug.
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Cloud Class® Course: CompTIA Cloud+

The CompTIA Cloud+ Basic training course will teach you about cloud concepts and models, data storage, networking, and network infrastructure.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now