Capture value from an email-like field at js

Asked

Viewed 724 times

0

I have the following HTML code with Angularjs:

<html ng-app> 
    //...
    <form name="myForm2">
        <input type="email" id="email" name="email" ng-model="formData.email" required/>
        <span ng-show="!myForm2.email.$error.required && myForm2.email.$error.email && myForm2.email.$dirty">invalid email {{formData.email}}</span>
    </form>
    //...
</html>

What I want is, if the user enters the wrong email field, the message "invalid email value_completed_no_field".

It turns out that the above code only returns the message "invalid email", I am not able to capture the field value.

What’s wrong with the code above?

  • I’m not sure, but I believe he’s setting the formData.email for null because the value of input is invalid. I will try to find something in the documentation that proves this, then put an answer.

  • @gabrielhof I think you’re right, I ran a test and put the correct e-mail and {{formData.email}} out of span (because it is hidden) and already appears. However I noticed that if you put "email@dominio" he considers it right and as we can see, it is not.

1 answer

1


I haven’t found any part of the Angularjs documentation that talks about this, but his default behavior is indefinite the property linked to the input when it does not have a valid value.

This is discussed in this Opinion of the Github and in that discussion in Google Groups.

That is, if myForm2.email.$invalid is true, the variable formData.email will be set to undefined. You can see it in this example.

Solution at Angular 1.3.x

If you are using version 1.3.x of Angular, there is a solution using ng-model-options. Just set the property allowInvalid for true:

<input type="email" id="email" name="email" ng-model-options="{allowInvalid: true}" ng-model="formData.email" required/>

That example demonstrates this solution by working.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.