Link to home
Start Free TrialLog in
Avatar of Bruce Gust
Bruce GustFlag for United States of America

asked on

How can I make this date validation feature "friendly" when it comes to deleting characters?

Here's the working code:

<!DOCTYPE html>
<html>
<head>
	<title>Bruce Gust</title>
	<link href="https://fonts.googleapis.com/css?family=Lato:400,400i,700" rel="stylesheet">
	<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
	<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
</head>

<body> 
Phone&nbsp;<input type="text" name="phone" maxlength="25" id="txtDate" style="width:150px;">
</body>

  <script>
$(document).ready(function() {
            $("#txtDate").keyup(function(){
                if ($(this).val().length == 2){
                    $(this).val($(this).val() + "/");
                }else if ($(this).val().length == 5){
                    $(this).val($(this).val() + "/");
                }
            });
});
  </script>
 

</html>

Open in new window


The ONLY thing that's in need of improvement is if the user goes to delete any characters in the date field. For example, if they enter "12" and they meant to enter "11," when you go to delete the 2 and the newly asserted "/," you can't do it! It's like it's getting stuck in this perpetual cycle.

Now, if you just highlight all of the characters and delete everything, that will work. But how can I craft the code so should a user go to delete a value, it doesn't get hung up?

Thanks!
Avatar of Bruce Gust
Bruce Gust
Flag of United States of America image

ASKER

BTW: Don't be distracted by the "Phone" label. It's a date validation script...
ASKER CERTIFIED SOLUTION
Avatar of Member_2_248744
Member_2_248744
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial