0

I'm trying to validate an email field by make sure the user is entering in a valid email by checking it against

/^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i

In standard JS I would use and event listener to know when the user has triggered a keyup but in Angular I suspect there's different ways to listen to the data via "two-way data binding". How do I accomplish this same task via an angular controller js?

2
  • There are at least 3 ways I can think of, but since you mention keyup, perhaps you might try this? docs.angularjs.org/api/ng/directive/ngKeyup#! Commented Apr 3, 2015 at 14:03
  • 2
    How about using input type="email", and let Angular do that for you, with its standard form validation framework? You're reinventing the wheel. Commented Apr 3, 2015 at 14:04

2 Answers 2

4

Have a look at input[email], angular's validation:

https://docs.angularjs.org/api/ng/input/input%5Bemail%5D

there's an ngChange option.

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

3 Comments

This looks good but why does angular think "user@m" is a valid email address? I tried it in the example at docs.angularjs.org/api/ng/input/input%5Bemail%5D
According to sphinx.mythic-beasts.com/~pdw/cgi-bin/emailvalidate, it is indeed valid.
Hmm, in the meantime I'm using your solution with accompanied data-ng-pattern="/^[_a-z0-9]+(\.[_a-z0-9]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$/"
0

There is a thing called $watch, or watchers. And you can have it "listen" for a model being changed

scope.$watch('name', function(newValue, oldValue) {
scope.counter = scope.counter + 1;
});

So in this example, whenever the model "name" changes, counter goes up by one. You see the other parameters passed, oldVal and newVal, you can cross-reference these against each other and if there is a new value,you can set you logic to do it, but that's your own decision. Just put you Regex check inside this function and change the model of the field from name to whatever yours is. *make sure it's in the right controller ^_^.

Comments

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.