1

I'm using ng-pattern to validate a field and display a message when it does not match a specific pattern using ng-messages. The issue I have is the form has a next button which is being disabled/enabled with ng-diabled"form.$invalid" so when the input is invalid the form is then invalid.

What I would like to achieve is to display a message with ng-message when ng-pattern is not matched but not set the form to invalid. Essentially I'm trying to provide a hint that the text input by the user might not be valid whilst not preventing the form from being submitted.

2 Answers 2

1

From what i can understand , you are using ng-disabled this means you want to disable button when form is invalid but for some specific condition you just want to show error message but not invalidate form

If that's the case just add a watcher for that ng-model value in your controller and toggle a variable to show or hide that error message

$scope.$watch('email', function() {
  if (email == '[email protected]') {
    flag = true;
  }
  else {
    flag = false;
  }
})

Note this is for specific case only, Avoid using watchers it slows down your app

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

2 Comments

Is there a better way of doing this? You have understood what I want to do exactly. It's basically and address entry form where certain fields are required and I want to encourage the user to enter a correctly formatted postal code but not prevent the form from being submitted as postal code matching is very ambiguous.
If you want to avoid watcher , use ng-change , though it is also a watcher but its angular inbuilt so memory consumption will be less
0

I think you want like this. here, this pattern for decimal value if it's not matching it won't allow to submit data.

<input class="form-control" type="dacimal" name="percentage" ng-model="percentage" ng-min="0.01" ng-pattern="/^[0-9]+(\.[0-9]{1,2})?$/" step="0.01" required>
<span class="alert-danger" ng-show="studentForm.$submitted || (studentForm.percentage.$dirty && studentForm.percentage.$invalid)">
  <span ng-show="studentForm.percentage.$error.required">Percentage is required !</span>
  <span ng-show="!studentForm.percentage.$valid">Invalid Percentage !</span>
</span>

1 Comment

Thanks for the comment but I was actually trying to avoid the default behavior of preventing making the form invalid and merely show a warning to the user! Kind of soft validation if you like. I ended up using @Shyam suggestion above and using ng-change with a RegExp check.

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.