write an ng-pattern to disallow whitespaces and special characters

前端 未结 3 909
南旧
南旧 2021-02-02 11:45

I am trying to get an angular ng-pattern to check that a username has no whitespaces or special characters. The following form return false if you enter whitespaces or special c

相关标签:
3条回答
  • 2021-02-02 12:18

    To surface the specific answer I was looking for, I already had the pattern suggested by Sniffer /^[a-zA-Z0-9]*$/, but angular still appeared to ignore leading/trailing whitespace. As Cristian mentions in the comments:

    Angular will trim the input model, meaning that the validation doesn't trigger for spaces. You can add an ng-trim="false" to the input to fix this.

    Note that Angular is trying to protect you by silently trimming whitespace by default. In my case, I want the user to be aware that the trailing whitespace is invalid.

    0 讨论(0)
  • 2021-02-02 12:18

    in case anyone needs to disallow user entering emails in the address field

    ng-pattern="/^[^@]+$/"

    <div ng-messages="vm.updateCC.mailingAddress.$error" ng-show="vm.updateCC.mailingAddress.$touched">
         <p class="validation-message" ng-message="pattern">Please enter a valid address</p>
    </div>
    
    0 讨论(0)
  • 2021-02-02 12:33

    Try the following pattern:

    /^[a-zA-Z0-9]*$/
    

    This allows only alphanumeric characters.

    0 讨论(0)
提交回复
热议问题