AngularJS form validation not working as expected

时间:2015-10-02 08:40:07

标签: angularjs

I am having trouble getting form validation to work correcty.

I have the following form:

<form name="testForm" novalidate>
    <input type="text" name="name" class="form-control" id="name" ng-model="name"
                placeholder="Enter a name for your topic discovery" required/>
    <p ng-show="testForm.name.$invalid" class="help-block">A name is reqiured for the topic discovery</p>
</form>

But the <p> element is never shown, what am I doing wrong?

3 个答案:

答案 0 :(得分:0)

您需要为input元素命名:

<input type="text" class="form-control" name="name" id="name" ng-model="name"
       placeholder="Enter a name for your topic discovery" required />

请记住,元素在testForm命名空间下注册了 name ,而不是ngModel,在您的情况下它们是相同的,但在大多数情况下它们是不同的。

答案 1 :(得分:0)

您忘了添加输入名称

<input type="text" name="name" class="form-control" id="name" ng-model="name"
                        placeholder="Enter a name for your topic discovery" required/>

完整示例:

<form name="testForm" novalidate>
        <input type="text" name="name" class="form-control" id="name" ng-model="name"
                    placeholder="Enter a name for your topic discovery" required/>
        <p ng-show="testForm.name.$touched && testForm.name.$invalid" class="help-block">A name is reqiured for the topic discovery</p>

答案 2 :(得分:0)

问题是你的类型属性值是&#34; text&#34;,这很难变得无效。将其更改为&#34;电子邮件&#34;例如,然后将name属性的值设置为某些&#34; myName&#34; (用于视觉差异)输入元素(如上所述)。您还可以为<p>元素的ng-show属性添加另一个条件,如下所示:

<p ng-show="testForm.myName.$invalid && testForm.myName.$dirty" class="help-block">A name is reqiured for the topic discovery</p>