Validate <input type=“number” /> with AngularJS and Pattern/RegEx

前端 未结 4 2001
野趣味
野趣味 2021-01-12 11:36

I have a input of type number, and I want to make sure it only accepts a number. I can do this fine on the Server side, but with AngularJS I can not get it to work.

相关标签:
4条回答
  • 2021-01-12 11:43

    Pattern don't work for input with type="number".
    You can use type="text" and than convert value to number

    0 讨论(0)
  • 2021-01-12 11:46

    Here is regexp to validate floating point numbers, both positive and negative:

    /^-?[0-9]\d*(\.\d+)?$/
    

    Use this regexp in 'text' input, example:

    <input type="text" ng-model="score" ng-pattern="/^-?[0-9]\d*(\.\d+)?$/" required/>
    
    0 讨论(0)
  • 2021-01-12 11:48

    You need to use anchors:

    /^[0-9]+$/
    
    • ^: Start-of-line anchor.
    • [0-9]+ One or more numbers between 0 and 9.
    • $: End-of-line anchor.

    So this matches the start of the string, then it matches the one or more digits, after that it looks for the end-of-string, so it matches a string containing only numbers and nothing else.

    Otherwise, /[0-9]+/ will match only a part of aa23423, more accurately the number 23423 and thus will give you valid.

    0 讨论(0)
  • 2021-01-12 12:03

    Try defining your regex as a scope variable In the controller, it worked for me.

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