I've this code:
<form name="test">
<input type="text" ng-model="code" name="code" ng-pattern="/^code_[0-9]+$/"/>
<div ng-show="test.code.$dirty && test.code.$invalid">
Error:
<span ng-show="test.code.$error.pattern">Pattern fail.</span>
</div>
</form>
I have 2 issues with this code:
Strings like " code_232 ", "code_232 " " code_232" pass the validation. I'm not expert with regex, so this could be an issue simply related to the regex i wrote: /^code_[0-9]+$/
If i start writing "code_23892" (a correct string), i get the error
message while i'm still writing (test.code.$error.pattern = true
). Is there a built-in way to avoid this? So my desidered behaviour is:
If i write "cod", and the input has still focus: no error
If i write "cod" and the input loses focus: error.
If i write "a", "ca", "coa" etc.: error, cause the pattern is already violated.
Is this already possible, or i've write a custome validation directive to achieve this?
Thanks in advance.
The reason that whitespace doesn't trigger a failed validation is because ng-model automatically trims the value. If you don't want that, you can add ng-trim="false"
to your <input />
. Note that ng-trim is a quite new attribute, so you might have to update your Angular version.
About your second question; I don't think you can avoid the validation to run during the time you type, but you could change your code to only display the error when the input looses focus. I don't think that something like ng-blur
and ng-focus
exists, but it should be pretty simple to implement them.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With