Always Learning
Always Learning

Reputation: 5601

Why isn't form submit blocked by an invalid input field in angularJS?

I'm trying to understand custom form validation in angularjs. I followed an example that defines a directive to set an input text field as valid or invalid based on whether it contains an 'e' character. That seems to work because the css styling changes based on the validity. However the form still allows the submit button to be pressed even when the field is invalid. The following plunker shows a simple example. It draws a red border for the input field if it's invalid.

Plunker: http://plnkr.co/edit/84NpBl9nmL5Qda96YF8d?p=preview

Note that the 'add' button is disabled if the text field is empty, which is due to the required attribute, but I wanted the button to be disabled also when the field is invalid. What am I missing? I guess I was hoping that required would mean "valid" rather than just "not empty".

Upvotes: 0

Views: 242

Answers (1)

Always Learning
Always Learning

Reputation: 5601

I've figured out how to do what I want. First, required only demands some value is present. To validate control disabling the submit button, I needed to use ng-disabled and have it call a js function to determine the state.

The angular directive for my input field now sets a variable to true or false to record whether the add button should be disabled, and that variable is what's checked in the nb-disabled test. It also continues to call $setValidity so that the css will still mark the field as invalid visually.

Here's a new plunker to show the changes. I also used ng-repeat to show how it will work if there are multiple forms in a repeat.

Plunker: http://plnkr.co/edit/HYYPvFFARL1m0WBr3WrM?p=preview

The key changes are the modifications to myDirective to change the scope.disableAdd[] values, and the ng-disabled="checkDisableAdd({{$index}})" attribute for the submit button.

Upvotes: 0

Related Questions