• 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
0
Pedro Chagas
Asked:
Pedro Chagas
1 Solution
 
Leonidas DosasCommented:
What is the echo value in the input?
0
 
Pedro ChagasWebmasterAuthor Commented:
Hi @Leonidas,
You can see the echo in attach image.
Can you please help me?

~JC
22-04-2018-21-55-12.png
0
 
Leonidas DosasCommented:
Check this function
function a(arg){ 
  var y,x,z;  
  arg=arg.split('-');
  y=arg[1].substr(-2);
  z=arg[1].substr(0,2);  
  x=arg[0]+'-'+z+'-'+y;
  return x;
}
console.log(a('2018-0222'));

Open in new window

0
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.
~JC
0
 
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

0
 
Julian HansenCommented:
Advice - don't put your code inline. Create a function for it and call that - it will be much easier to debug.
0
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