简体   繁体   English

自动生成的表单的AngularJS表单验证

[英]AngularJS form validatation of auto-generated form

I am trying to validate an auto-generated form (via AngularJS v1.3 ) which inputs' names are in format: 我正在尝试验证自动生成的表单(通过AngularJS v1.3 ),该表单的输入名称格式如下:

form_name[field_name]

The very basic example would be: 最基本的示例是:

<form name="morgageCalculator">
        <input type="text" class="form-control" 
            name="morgageCalculator[homeValue]" value="0"
            data-ng-model="data.homeValue" required="required"/>
</form>

As you can see, the input name is morgageCalculator[homeValue] . 如您所见,输入名称为morgageCalculator[homeValue] Now I would like to add an error message below it: 现在,我想在下面添加一条错误消息:

<div class="error"
     data-ng-show="!morgageCalculator.morgageCalculator[homeValue].$pristine && morgageCalculator.morgageCalculator[homeValue].$invalid">
    Please enter a number
</div>

For very obvious syntax reasons this expression is not valid: 出于非常明显的语法原因,此表达式无效:

morgageCalculator.morgageCalculator[homeValue].$pristine

But this one also does not work: 但这也行不通:

morgageCalculator["morgageCalculator[homeValue]"].$pristine

So, the question , is there any sane way of accessing those fields? 因此, 问题是,是否有任何明智的方式访问这些字段? I wouldn't mind moving the validation to some controller function, but I was faced with same issue of inability to access field object. 我不介意将验证移至某些控制器功能,但是我面临着无法访问字段对象的相同问题。

Any help/hint would be greatly appreciated. 任何帮助/提示将不胜感激。

With help of @dfsq from comment section, I was able to find the error. 借助注释部分中的@dfsq,我能够找到错误。 Unlike my SO question, my code was missing data-ng-model . 与我的SO问题不同,我的代码缺少data-ng-model

Validation will not fire at all if input was not bound to model.... 如果输入未绑定到模型,则验证将不会触发。

The correct snippet: 正确的代码段:

<form name="morgageCalculator">
    <input type="text" class="form-control" 
        name="morgageCalculator[homeValue]" value="0"
        data-ng-model="data.homeValue" required="required"/>


    <div class="error"
        data-ng-show="!morgageCalculator['morgageCalculator[homeValue]'].$pristine && morgageCalculator['morgageCalculator[homeValue]'].$invalid">
            Please enter a number
    </div>
</form>

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

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