简体   繁体   English

基于AngularJs中的正则表达式在文本框中只允许一个数值

[英]To allow only one numeric value in text box based on regular expression in AngularJs

I'm using ng-pattern :我正在使用ng-pattern

 <input type="text" ng-model="price" name="price_field" ng-pattern-restrict="/^[4]*$/" required only-digits>

Please let me know what to do that it does not accept any other numbers except 4. I am using directive for digits that is only-digits.请让我知道该怎么做,它不接受除 4 之外的任何其他数字。我使用的数字指令仅为数字。

EDIT: SORRY WRONG ANGULAR VERSION - but if you can transform this to angularjs it will be work!编辑:抱歉错误的角度版本 - 但如果你可以将它转换为 angularjs 它将起作用!

You can use (input) event in you HTML input element您可以在 HTML 输入元素中使用(input)事件

<input type="number" (input)="check($event)">

Than in your ts you cehck value of input比在您的 ts 中您检查输入的值

  check(event) {
    console.log(event);
    if (+event.data !== 4) {
      event.target.value = '';
    }
  }

The pattern which you are mentioned is not a valid regex pattern.您提到的模式不是有效的正则表达式模式。 Instead of that try to use this /^([4]){1}?$/ Hope you will get it.而不是尝试使用这个/^([4]){1}?$/希望你会得到它。

 <input type="text" ng-model="price" name="price_field" ng-pattern-restrict="/^([4]){1}?$/" required only-digits>

Try to use below restrict pattern :尝试使用以下限制模式:

<input type="text" ng-model="price" name="price_field" ng-pattern-restrict="^[4]{1}?$" required only-digits>

And below validation message :和下面的验证消息:

<div ng-messages="myForm.price_field.$error">
    <span ng-message="pattern">Not a valid number!</span>
</div>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM