AngularJs:在数字输入字段中设置验证的条件最小值和最大值

AngularJs : Set conditional min and max value for validation in number input field

本文关键字:条件 最小值 最大值 验证 设置 数字输入 字段 AngularJs      更新时间:2023-09-26

我创建了一个网页,其中包含一个具有两个数字输入字段field1field2的表单。我正在对这些字段进行验证。field1具有min值1和max值100000,但field2应该具有min值,即field1或1的max,任何大于max的值都是100000。我试图将field1ng-model分配为field2min,但不起作用。

<div class="row">
  <div>
    <input ng-model="priceminrange" name="priceminrange" type="number"
    class="form-control" value="" placeholder="MinRange" min="1" max="100000">
    <span ng-show="form.priceminrange.$error.number">The value is not a valid number</span> 
    <span ng-show="form.priceminrange.$error.min || form.priceminrange.$error.max">
    The value must be in range 1 to 100000</span>
  </div>
  <div>
    <input ng-model="pricemaxrange" name="pricemaxrange" type="number"
    class="form-control" value="" placeholder="MaxRange" min={{priceminrange}} max="100000">
    <span ng-show="form.pricemaxrange.$error.number">The value is not a valid number</span> 
    <span ng-show="form.pricemaxrange.$error.min || form.pricemaxrange.$error.max">
    The value must be in range {{priceminrange}} to 100000</span>
    form.pricemaxrange.$error = {{form.pricemaxrange.$error}}
  </div>
</div>

你很接近。对象priceminrange是一个Angular对象,它包含多个方法和属性,所有这些方法和属性都与模型有关。所需的属性称为$modelValue,其中包含用户在将其解析为正确的数据类型(本例中为数字)后输入的值。

假设您已经将输入元素封装在一个名为"form"的表单中,这样的操作应该会起作用

<input ng-model="pricemaxrange" type="number" min="{{form.priceminrange.$modelValue}}">

试试这个

在控制器上创建作用域。

$scope.priceminrange = 1;