2

Im using AngularUI Utils in attempt to mask a date input. However, when I try to test a regex against the field to validate the date format, it returns false every time.

HTML

<div class="row form-group">
  <div class="col-xs-12">
    <label>Date of Birth</label>
    <input class="form-control" ng-model="vm.dateOfBirth" ui-mask="99/99/9999" placeholder="MM/DD/YYYY" />
  </div>
</div>

AngularJS

var dateRegex = /^\d{2}\/\d{2}\/\d{4}$/;

var vm = this;
vm.dateOfBirth = "";

vm.validateInput = function () {
    return dateRegex.test(vm.dateOfBirth);
}

Is there any other way to validate this input?

1 Answer 1

4

I found a solution, but seems a bit hacky. Apparently if the model does not match the mask regex, the variable will be undefined or an empty string (when you backspace through the mask).

vm.validateInput = function () {
    return typeof vm.dateOfBirth !== "undefined" && vm.dateOfBirth != "";
}

This seems to do the trick, but it will only work for the very simple regular expressions that are accepted by AnguarUI masks. I would love to know if there is another way to apply additional regex validation on top of the mask like I was attempting to do originally.

Sign up to request clarification or add additional context in comments.

2 Comments

Hey awesome catch! I've had the same EXACT problem... quick question: Where exactly do you implement this function? Do you wrap ng-model="vm.dateOfBirth" with this (like ng-model="vm.validateInput(vm.dateOfBirth)") in the HTML input element?
I'm using it on a form submission. So my code looks more like <form ng-submit="vm.validateInput(vm.dateOfBirth)">...</form>. But you could bind it to button clicks or blur events on the text box and prevent form submission if the date is invalid.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.