Javascript validate user input

Hi Everyone

I recently ask a question about checking user input. Function is called onkeyup.  If any invalid character is entered then it replaces it with an empty space.

http://www.experts-exchange.com/questions/28688349/Javascript-Check-User-Input.html

I have amended the code to do a few things - Point 1 - 6 works fine

1) Format is entered in mm/yy
2) If first character is a zero then second digit can only be 1-9
3) If first character is a one then the second digit can only be 0-2
4) Third character is always a /
5) Works out the last two digits of the current year stored first digit in one and second digit in two
6) When the user goes to enter the first year digit (position 4) they can only enter a value greater than or equal to the first digit of this year.

7) On the last else if statement if I enter the values 12/11 it shows the alert Done6 and the answer then converts to 2/11 instead of 12/1

If I enter 12/12 it shows the alert Done6 then it converts to 1/12 instead of 12/1
If I enter 03/13 it shows the alert Done6 then it converts to 0/13 instead of 03/1

Can any one shed any light on why this could be happening.

Many thanks


function checkExpiry(ob) {
    
   var invalidone = /[^0-1]/gi;
   var invalidtwo = /[^0-2]/gi;
   var invalidthree = /[^1-9]/gi;
   var invalidfour = /[^/]/gi;
   
   var len = ob.value.length;
   // alert(len);
   // alert(ob.value.charAt(len-1));
    
   var yy = (new Date().getFullYear().toString()).substring(2);
   var one = (yy.toString()).slice(0,1);
   var two = (yy.toString()).slice(1,2);
   
   if(len == 1 && invalidone.test(ob.value)) 
   {
       ob.value = ob.value.replace(ob.value.charAt(len-1),"");
       alert("Done1");
   }
    
  else if(len == 2 && ob.value.charAt(len-2)== 1 && invalidtwo.test(ob.value.charAt(len-1)))
  {
       ob.value = ob.value.replace(ob.value.charAt(len-1),"");
       alert("Done2");
   }
    
   else if(len == 2 && ob.value.charAt(len-2)== 0 && invalidthree.test(ob.value.charAt(len-1))) 
   {
       ob.value = ob.value.replace(ob.value.charAt(len-1),"");
       alert("Done3");
   }
    
   else if(len == 3 && invalidfour.test(ob.value.charAt(len-1))) 
   {
       ob.value = ob.value.replace(ob.value.charAt(len-1),"");
       alert("Done4");
   }
    
   else if(len == 4 && ob.value.charAt(len-1)<one) 
   {
       ob.value = ob.value.replace(ob.value.charAt(len-1),"");
       alert("Done5");
   }
    
   else if(len == 5 && ob.value.charAt(len-2)==one && ob.value.charAt(len-1)< two) 
   {
       ob.value = ob.value.replace(ob.value.charAt(len-1),"");
       alert("Done6");
   }
}

Open in new window

Lisa BAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

skijCommented:
Even with the validation, using a text input could be confusing to users.  Why not use select/options?
<select name="selectMonth" id="selectMonth">
    <option value="01">January</option>
    <option value="02">February</option>
    <option value="03">March</option>
    <option value="04">April</option>
    <option value="05">May</option>
    <option value="06">June</option>
    <option value="07">July</option>
    <option value="08">August</option>
    <option value="09">September</option>
    <option value="10">October</option>
    <option value="11">November</option>
    <option value="12">December</option>
</select>
<select name="selectYear" id="selectYear">
    <option value="2015">2015</option>
    <option value="2016">2016</option>
    <option value="2017">2017</option>
    <option value="2018">2018</option>
    <option value="2019">2019</option>
    <option value="2020">2020</option>
</select>

Open in new window

skijCommented:
Here is an example:
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>

<select id="selectMonth" onchange="updateMonthYear()">
    <option value="01">January</option>
    <option value="02">February</option>
    <option value="03">March</option>
    <option value="04">April</option>
    <option value="05">May</option>
    <option value="06">June</option>
    <option value="07">July</option>
    <option value="08">August</option>
    <option value="09">September</option>
    <option value="10">October</option>
    <option value="11">November</option>
    <option value="12">December</option>
</select>
<select id="selectYear" onchange="updateMonthYear()">
    <option value="15">15</option>
    <option value="16">16</option>
    <option value="17">17</option>
    <option value="18">18</option>
    <option value="19">19</option>
    <option value="20">20</option>
</select>
<input name="monthYear" id="monthYear" type="text" readonly="readonly" />


<script type="text/javascript">
function updateMonthYear() {
  document.getElementById('monthYear').value=document.getElementById('selectMonth').value+'/'+document.getElementById('selectYear').value;
}
updateMonthYear()
</script>

</body>
</html>

Open in new window

https://jsfiddle.net/q9e2ymjh/
Lisa BAuthor Commented:
Hi skij

Apologies for not replying sooner.

Currently all our users enter the expiry date in access as mm/yy as access allows input masking.  

I am integrating our current applications into new third party software which is web based - I would imagine that if the user is used to entering mm/yy then they would want it keep it that way - I will need to find out about this.

If I was to use two list boxes and write the value in to a text box I would still need to validate the text box which is what I was originally trying to do.  This new software will allow you to use their current controls that has validation built in eg numeric only, text only, compulsory field etc but if you need any other validation then you need to build your own control.  As I want input masking then I need to build my own control.

1) Using the two list boxes how would I stop the user entering 05/15 considering we are now in June?
2) Do you know why the code I originally had does now work on the last statement?

Thanks
Big Business Goals? Which KPIs Will Help You

The most successful MSPs rely on metrics – known as key performance indicators (KPIs) – for making informed decisions that help their businesses thrive, rather than just survive. This eBook provides an overview of the most important KPIs used by top MSPs.

Lisa BAuthor Commented:
sorry in comment 2 meant to write

2) Do you know why the code I originally had does not work on the last statement?
skijCommented:
Try this:
<!DOCTYPE html>
<head>
<title></title>
</head>
<body>

<input type="text" onkeyup="validateMMsYY(this)" onblur="validateMMsYYValid(this)" />

<script type="text/javascript">

function validateMMsYY(obj) {
  var v1 = obj.value.substr(0,2);
  if(v1.length>=2) {
    v1 = String("00"+ v1.substr(0,2).replace(/[^0-9]/g, '')).slice(-2);
    if(Number(v1)<1) v1="01";
    if(Number(v1)>12) v1="12";
  }
  if(obj.value.length==3 && (obj.value.substr(2,1).match(/[0-9]/)))  obj.value = String(v1 + "/" + obj.value.substr(2,1))
  var v3 = obj.value.substr(3,2);
  if(v3.length>=2) {
    v3 = String("00"+ v3.substr(0,2).replace(/[^0-9]/g, '')).slice(-2);
  }
  obj.value = String(v1 + "/" + v3).substr(0,obj.value.length);
}

function validateMMsYYValid(obj) {
  if (!/^(0[1-9]|1[0-2])\/\d{2}$/.test(obj.value) ) {
   alert('The date must be in mm/yy format.');
   obj.value='';
  }
}

</script>

</body>
</html>

Open in new window

https://jsfiddle.net/rd8r91c8/
skijCommented:
This will make sure that the date is in the future:
<!DOCTYPE html>
<head>
<title></title>
</head>
<body>

<input type="text" onkeyup="validateMMsYY(this)" onblur="validateMMsYYValid(this)" />

<script type="text/javascript">

function validateMMsYY(obj) {
  var v1 = obj.value.substr(0,2);
  if(v1.length>=2) {
    v1 = String("00"+ v1.substr(0,2).replace(/[^0-9]/g, '')).slice(-2);
    if(Number(v1)<1) v1="01";
    if(Number(v1)>12) v1="12";
  }
  if(obj.value.length==3 && (obj.value.substr(2,1).match(/[0-9]/)))  obj.value = String(v1 + "/" + obj.value.substr(2,1))
  var v3 = obj.value.substr(3,2);
  if(v3.length>=2) {
    v3 = String("00"+ v3.substr(0,2).replace(/[^0-9]/g, '')).slice(-2);
    var date = new Date();
    var currentYear = Number(date.getFullYear().toString().substr(2,2));
    if(Number(v3)<currentYear) v3=currentYear;
  }
  obj.value = String(v1 + "/" + v3).substr(0,obj.value.length);
}

function validateMMsYYValid(obj) {
  if (!/^(0[1-9]|1[0-2])\/\d{2}$/.test(obj.value) ) {
   alert('The date must be in mm/yy format.');
   obj.value='';
  }
  else {
   var rightnow = new Date();
   var backthen = new Date( 2000+Number(obj.value.substr(3,2)), (Number(obj.value.substr(0,2))-1));
   if (rightnow>backthen)
   {
    alert("You must enter a date that is in the future.");
    obj.value='';
   }
  }
}

</script>

</body>
</html>

Open in new window

https://jsfiddle.net/nv5j3m2d/
Lisa BAuthor Commented:
Hi skij

I have one issue when I put in 06/15 it says I must enter a date in the future.  As cards are valid to the end of the month I would need this current month to be valid.
skijCommented:
Simply remove -1 from the line that begins with  var backthen
<!DOCTYPE html>
<head>
<title></title>
</head>
<body>

<input type="text" onkeyup="validateMMsYY(this)" onblur="validateMMsYYValid(this)" />

<script type="text/javascript">

function validateMMsYY(obj) {
  var v1 = obj.value.substr(0,2);
  if(v1.length>=2) {
    v1 = String("00"+ v1.substr(0,2).replace(/[^0-9]/g, '')).slice(-2);
    if(Number(v1)<1) v1="01";
    if(Number(v1)>12) v1="12";
  }
  if(obj.value.length==3 && (obj.value.substr(2,1).match(/[0-9]/)))  obj.value = String(v1 + "/" + obj.value.substr(2,1))
  var v3 = obj.value.substr(3,2);
  if(v3.length>=2) {
    v3 = String("00"+ v3.substr(0,2).replace(/[^0-9]/g, '')).slice(-2);
    var date = new Date();
    var currentYear = Number(date.getFullYear().toString().substr(2,2));
    if(Number(v3)<currentYear) v3=currentYear;
  }
  obj.value = String(v1 + "/" + v3).substr(0,obj.value.length);
}

function validateMMsYYValid(obj) {
  if (!/^(0[1-9]|1[0-2])\/\d{2}$/.test(obj.value) ) {
   alert('The date must be in mm/yy format.');
   obj.value='';
  }
  else {
   var rightnow = new Date();
   var backthen = new Date( 2000+Number(obj.value.substr(3,2)), (Number(obj.value.substr(0,2))));
   if (rightnow>backthen)
   {
    alert("You must enter a date that is in the future.");
    obj.value='';
   }
  }
}

</script>

</body>
</html>

Open in new window

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Lisa BAuthor Commented:
Hi

Works perfect - Thanks very much for the help I really appreciate it
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
JavaScript

From novice to tech pro — start learning today.