简体   繁体   English

基本角度形式验证不起作用

[英]basic angular form validation not working

Template: 模板:

<div class="container">
<div class="row">
    <div class="col s12">
        <p>Add products here</p>
        <form name="addProductForm" data-ng-submit="addProduct(addProductForm.$valid)" novalidate>
            <label for="productName">Name</label>
            <input name="productName" type="text" placeholder="name" data-ng-model="product.name" required="" />
            <p ng-show="addProductForm.name.$valid" >Wrong Name</p>
            <p ng-show="addProductForm.name.$invalid" >Write Name</p>
            <label for="productName">Type</label>
            <input name="productName" type="text" placeholder="name" data-ng-model="product.type" required="" />
            <input type="submit" data-ng-disabled="addProductForm.$invalid" class="btn" value="Add" />
        </form>
    </div>
</div>

I have added two p tags one with valid and other with invalid but both of them are not showing up. 我添加了两个p标签,一个带有有效标签,另一个带有无效标签,但是它们都没有显示出来。 Any help will be appreciated. 任何帮助将不胜感激。

The problem is in your "name" property of your inputs. 问题出在您输入的“名称”属性中。

<p ng-show="addProductForm.productName.$invalid" >Wrong Name</p>
<p ng-show="addProductForm.productType.$invalid" >Write Name</p>


<input name="productType" type="text" data-ng-model="product.type" required="" />
<input name="productName" type="text" placeholder="name" data-ng-model="product.name" required="" />

The "name" property has to match whatever you are evaluating in the condition. “名称”属性必须匹配您在条件中评估的任何内容。

Here is a working fiddle: 这是一个工作的小提琴:

http://jsfiddle.net/rskhLcnz/ http://jsfiddle.net/rskhLcnz/

I suggest you use ngMessages instead of ngShow and remember the field names 我建议您使用ngMessages而不是ngShow并记住字段名称

    <form name="myForm" ng-init="formData = {}">
      <input name="productName" type="text" ng-model="formData.productName" placeholder="Product name" required>
      <div ng-messages="myForm.productName.$error">
        <div ng-message="required">This field is required</div>
      </div>
      <input name="productType" type="text" ng-model="formData.productType" placeholder="Product type" required>
      <div ng-messages="myForm.productType.$error">
        <div ng-message="required">This field is required</div>
      </div>
      <input type="submit" ng-disabled="myForm.$invalid" class="btn" value="Add" />
    </form>
    <pre>{{formData}}</pre>

Example

AngularJS Form Validation with ngMessages 使用ngMessages进行AngularJS表单验证

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

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