uniapp表单验证

本文介绍了如何在UniApp中实现一个简单的表单验证,包括使用v-model监听输入,submitForm方法检查并提示用户填写缺失的字段,以及uni.showToast进行错误提示。着重于基础验证逻辑和实践应用。
摘要由CSDN通过智能技术生成

以下是一个简单的uniapp表单验证示例:

<template>
  <view class="uni-form">
    <view class="uni-form-item">
      <view class="uni-form-label">用户名</view>
      <input type="text" v-model="username" placeholder="请输入用户名" />
    </view>
    <view class="uni-form-item">
      <view class="uni-form-label">密码</view>
      <input type="password" v-model="password" placeholder="请输入密码" />
    </view>
    <view class="uni-form-item">
      <button type="primary" @click="submitForm">登录</button>
    </view>
  </view>
</template>
 
<script>
export default {
  data() {
    return {
      username: '',
      password: ''
    };
  },
  methods: {
    submitForm() {
      if (!this.username) {
        uni.showToast({
          title: '请输入用户名',
          icon: 'none'
        });
        return;
      }
      if (!this.password) {
        uni.showToast({
          title: '请输入密码',
          icon: 'none'
        });
        return;
      }
      // 校验通过,提交表单
      console.log('用户名:' + this.username);
      console.log('密码:' + this.password);
    }
  }
};
</script>
 
<style scoped>
.uni-form {
  background-color: #fff;
  padding: 20px;
  border-radius: 10px;
}
 
.uni-form-label {
  width: auto;
  margin-right: 20px;
}
 
.uni-form-item {
  display: flex;
  flex-direction: row;
  align-items: center;
  margin-bottom: 20px;
}
 
button {
  width: 100%;
  padding: 10px;
  background-color: #007aff;
  color: #fff;
  border-radius: 20px;
  border: none;
}
</style>

在上面的示例中,我们定义了一个包含两个输入框和一个提交按钮的表单,当用户点击提交按钮时,我们首先校验表单数据是否合法,如果校验不通过,我们会使用uni.showToast()方法弹出提示消息。如果校验通过,我们就可以提交表单了。

需要注意的是,这个示例只是一个简单的表单验证示例,实际应用中,我们还需要进行更加复杂的表单验证,例如手机号码、邮箱、身份证号码等的验证。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值