Disable button in angularjs with ng-pattern

597 Views Asked by At

I'm trying to disable the button when the textarea doesn't match with the pattern. I have tried below but button is disabled only when there is nothing typed in the textarea.

Any help?

Pattern: Should not allow . , ' " :

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>

<body ng-app="">

  <form name="myForm">

    <textarea rows="5" cols="50" name="notes" ng-model="notes" id="notes" ng-pattern="/^[a-zA-Z0-9.,:&apos;&quot;]*$/" required></textarea>

    <span ng-show="myForm.notes.$error.required">Notes is required</span>
    <span ng-show="myForm.notes.$error.pattern">Invalid Notes</span>
    <button type="button" ng-disabled="myForm.$invalid">Click me</button>
  </form>

</body>

1

There are 1 best solutions below

0
On

It looks like your reg expression is wrong. Your expression allows all alphanumeric as well as the special symbols you include. An underscore would invalidate your regex and disable your button.

This regex can be used to allow any character except those found inside the character set (the ^ inside the brackets matches on any character that is not included):

/^[^.,':"]*$/

Of course, you need to escape the quote when encoding into HTML.

<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>  
<body ng-app="">

<form name="myForm">

<textarea rows="5" cols="50" name="notes" ng-model="notes" id="notes" ng-pattern="/^[^.,':&quot;]*$/" required
></textarea>

<span ng-show="myForm.notes.$error.required">Notes is required</span>
<span ng-show="myForm.notes.$error.pattern">Invalid Notes</span>
<button type="button" ng-disabled="myForm.$invalid">Click me</button>
</form>

</body>
</html>