date mask with validation

2.1k Views Asked by At

I used to use this solution by adding the call to a blur in the field, and if it returned false, I would show a tooltip stating that the date is invalid

function date(ele){
var dateRegex = /^(?=\d)(?:(?:31(?!.(?:0?[2469]|11))|(?:30|29)(?!.0?2)|29(?=.0?2.(?:(?:(?:1[6-9]|[2-9]\d)?(?:0[48]|[2468][048]|[13579][26])|(?:(?:16|[2468][048]|[3579][26])00)))(?:\x20|$))|(?:2[0-8]|1\d|0?[1-9]))([-.\/])(?:1[012]|0?[1-9])\1(?:1[6-9]|[2-9]\d)?\d\d(?:(?=\x20\d)\x20|$))?(((0?[1-9]|1[012])(:[0-5]\d){0,2}(\x20[AP]M))|([01]\d|2[0-3])(:[0-5]\d){1,2})?$/;
return dateRegex.test(ele.val());
}

The problem is that in this project I will need to use an old version of the bootstrap in which I don't have a tooltip.

I was thinking about copying the css of the newest bootsrap to create my own tooltip, but before that I want to find out if anyone knows a better way to resolve this date validation. the best solution is to make a mask for the input along with the validation and already displaying something like a tooltip or html5 message warning that the date is invalid.

I want to know if there is any way to implement a date mask that validates and returns to the user if the date is invalid and do not allow a submit, just like when we use a required in the field. Is there an implementation or library that does this?

something like invalide-feedback or valid-tooltip for date

1

There are 1 best solutions below

0
On BEST ANSWER

If you ask for something custom, it could be done like shown on MDN: Client-side form validation. I threw this quickly together and did not spend time on making it look nice but it works using the Constraint Validation API and your JS function just to show you can mix and match.

// There are many ways to pick a DOM node
const form = document.getElementsByTagName('form')[0];

const date = document.getElementById('date');
const dateError = document.getElementById('dateError');
const dateGroup = document.querySelector('.form-group');

date.addEventListener('input', function(event) {
    // Each time the user types something, we check if the form fields are valid.
    if (date.validity.valid && dateValidator(date)) {
        dateGroup.classList.remove("has-error");

        // In case there is an error message visible, if the field is valid, we remove it
        dateError.innerHTML = '';
        dateError.className = 'error'; // Reset the visual state of the message

    } else {
        // If there is still an error, show the correct error
        showError();
    }
});

form.addEventListener('submit', function(event) {
    // if the date field is valid, we let the form submit
    if (!date.validity.valid) {
        // If it isn't, we display an appropriate error message
        showError();
        // Then we prevent the form from being sent by canceling the event
        event.preventDefault();
    }
});

function showError() {
    if (date.validity.valueMissing) {
        // If the field is empty display the following error message.
        dateError.textContent = `Value missing.`;
        dateGroup.classList.add("has-error");
    } else if (date.validity.typeMismatch) {
        // If the field doesn't contain a date isplay the following error message.
        dateError.textContent = `Type mismatch.`;
        dateGroup.classList.add("has-error");
    } else if (date.validity.tooShort) {
        // If the data is too short display the following error message.
        dateError.textContent = `Too short. `;
        dateGroup.classList.add("has-error");
    } else if (!dateValidator(date)) {
        dateError.textContent = `Wrong Format.`;
        dateGroup.classList.add("has-error");
    }

    // Set the styling appropriately
    dateError.className = 'error active';
};

function dateValidator(ele) {
    var dateRegex = /^(?=\d)(?:(?:31(?!.(?:0?[2469]|11))|(?:30|29)(?!.0?2)|29(?=.0?2.(?:(?:(?:1[6-9]|[2-9]\d)?(?:0[48]|[2468][048]|[13579][26])|(?:(?:16|[2468][048]|[3579][26])00)))(?:\x20|$))|(?:2[0-8]|1\d|0?[1-9]))([-.\/])(?:1[012]|0?[1-9])\1(?:1[6-9]|[2-9]\d)?\d\d(?:(?=\x20\d)\x20|$))?(((0?[1-9]|1[012])(:[0-5]\d){0,2}(\x20[AP]M))|([01]\d|2[0-3])(:[0-5]\d){1,2})?$/;
    return dateRegex.test(ele.value); //TODO: Update ele.val() if it's jquery or whatever
}

$("form").submit(function (e) {
   var valid = date.validity.valid && dateValidator(date);
   // do your validation here ...
   if (!valid) {
      e.preventDefault();
      return false;
   }
}); 
input[type=text]{
  -webkit-appearance: none;
  appearance: none;

  width: 140px;
  border: 1px solid #333;
  margin: 0;
  font-size: 90%;

  box-sizing: border-box;
}
/* This is the style of our error messages */
.error {
  width  : 100%;
  padding: 0;

  font-size: 80%;
  color: white;
  background-color: #900;
  border-radius: 0 0 5px 5px;

  box-sizing: border-box;
}
.error.active {
  padding: 0.3em;
}
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="utf-8">
    <title>JavaScript form validation - checking date [mm/dd/yyyy or mm-dd-yyyy format]</title>
    <!-- Latest compiled and minified CSS -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
    <script src="https://code.jquery.com/jquery-1.12.4.min.js" integrity="sha256-ZosEbRLbNQzLpnKIkEdrPv7lOy9C27hHQ+Xp8a4MxAQ=" crossorigin="anonymous"></script>
    <!-- Latest compiled and minified JavaScript -->
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
</head>

<body onload='document.form.date.focus()'>
    <form name="form" action="#">
        <label for="mail">
            <p>Please enter a date:</p>
            <div class="form-group has-error has-feedback">
                <label class="col-sm-4 control-label" for="inputError">Date:</label>
                <div class="col-sm-8">
                    <input type="text" class="form-control" id="date" name="date" required minlength="10" placeholder="DD/MM/YYYY"> <span class="error" id="dateError" aria-live="polite"></span> </div>
            </div>
        </label>
        <br>
        <input type="submit" name="submit" value="Submit" /> </form>
</body>
</html>

If that's not good enough you might look into custom Bootstrap plugins like FormValidation (available for v3/4)