uniapp表单验证

以下是一个简单的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()方法弹出提示消息。如果校验通过,我们就可以提交表单了。

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

相关推荐
码路飞21 分钟前
热榜全是 OpenClaw,但我用 50 行 Python 就造了个桌面 AI Agent 🤖
java·javascript
前端Hardy1 小时前
别再忽略 Promise 拒绝了!你的 Node.js 服务正在“静默自杀”
前端·javascript·面试
前端Hardy1 小时前
别再被setTimeout闭包坑了!90% 的人都写错过这个经典循环
前端·javascript·vue.js
小林coding1 小时前
专为程序员打造的简历模版来啦!覆盖前端、后端、测开、大模型等专业简历
前端·后端
前端Hardy1 小时前
你的 Vue 组件正在偷偷吃掉内存!5 个常见的内存泄漏陷阱与修复方案
前端·javascript·面试
RaidenLiu1 小时前
Flutter Platform Channel 底层架构解析 —— 从 BinaryMessenger 到跨平台消息通信机制
前端·flutter·前端框架
bluceli1 小时前
CSS容器查询:响应式设计的新范式
前端·css
Tapir1 小时前
被 Karpathy 下场推荐的 NanoClaw 是什么来头
前端·后端·github
前端人类学1 小时前
深入解析JavaScript中的null与undefined:区别、用法及判断技巧
前端·javascript
ssshooter2 小时前
Tauri 项目实践:客户端与 Web 端的授权登录实现方案
前端·后端·rust