温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

怎么在ionic中使用angularjs实现表单验证

发布时间:2021-03-25 17:25:27 来源:亿速云 阅读:165 作者:Leah 栏目:web开发

本篇文章为大家展示了怎么在ionic中使用angularjs实现表单验证,内容简明扼要并且容易理解,绝对能使你眼前一亮,通过这篇文章的详细介绍希望你能有所收获。

需引入angular forms库,因为ionic会自动默认引入。

<header [title]="title"></header>

 <ion-content scroll="false">
 <!--<form>-->
  <ion-item>
  <ion-input type="text" class="form-control"
     name="username" #username="ngModel"
     required maxlength="10" minlength="6"
     placeholder="用户名"
     [(ngModel)]="user.username"
     ></ion-input>

  </ion-item>
  <p>ahdasidhasidashdudi</p>

  <ion-item>
  <ion-input type="password" class="form-control"
     name="password" #password="ngModel"
     required maxlength="16" minlength="6"
     placeholder="密码" [(ngModel)]="user.password"></ion-input>
  </ion-item>

  <ion-item>
  <ion-label>记住密码</ion-label>
  <ion-toggle [(ngModel)]="pepperoni"></ion-toggle>
  </ion-item>

  <button ion-button block (click)="login()">登录</button>
  <ion-item>
  <button ion-button icon-start outline (click)="goRegistered()">
   去注册
  </button>

  <button ion-button icon-end outline>
   忘记密码
  </button>
  </ion-item>
  <h2 class="errorMessage">{{promptMessage}}</h2>
  <span *ngIf="username.invalid && (username.dirty || username.touched)"
   class="errorMessage">用户名必须为6到10位</span>
  <span *ngIf="password.invalid && (password.dirty || password.touched)" class="errorMessage">
  密码必须为6-16位
  </span>
 <!--</form>-->


 </ion-content>

运行效果如下:

怎么在ionic中使用angularjs实现表单验证

3核心属性

可以看到[(ngModel)]="user.username"作用是绑定了我们在ts文件中定义的变量。

#username="ngModel"的作用是把我们绑定的模型值命名成username,变成了一个FormControl对象,这里不必纠结下节会讲。

required 验证是否为空 maxlength="10" 最大长度 minlength="6"最小长度。这些都是我们需要验证的条件。

*ngIf="username.invalid && (username.dirty || username.touched)"

*ngIf标签等于true时将错误信息显示出来username.invalid表示验证不合法返回true,username.dirty 判断是否改变了这个参数的值,username.touched表示是否有碰过表单,作用在于,刚打开表单页面是,里面参数都是空的,但无需显示错误信息。

进入model.d.ts文件看到部分源码如下

/**
  * A control is `valid` when its `status === VALID`.
  *
  * In order to have this status, the control must have passed all its
  * validation checks.
  */
 readonly valid: boolean;
 /**
  * A control is `invalid` when its `status === INVALID`.
  *
  * In order to have this status, the control must have failed
  * at least one of its validation checks.
  */
 readonly invalid: boolean;

valid属性表示参数值校验后结果不通过为false,通过为true。

invalid则表示参数值校验不通过为true,通过为false。

 /**
  * A control is `dirty` if the user has changed the value
  * in the UI.
  *
  * Note that programmatic changes to a control's value will
  * *not* mark it dirty.
  */
 readonly dirty: boolean;
 /**
 * A control is marked `touched` once the user has triggered
 * a `blur` event on it.
  */
 readonly touched: boolean;

上述内容就是怎么在ionic中使用angularjs实现表单验证,你们学到知识或技能了吗?如果还想学到更多技能或者丰富自己的知识储备,欢迎关注亿速云行业资讯频道。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI