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

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

相关推荐
William_Xu32 分钟前
Vue 2 与 Vue 3 生命周期对比
前端
Hilaku1 小时前
为什么你的大文件断点续传,一遇到弱网就崩溃?
前端·javascript·程序员
胡哈2 小时前
React Compiler:让开发者忘掉 memo 这件事
前端·react.js
xiyueyezibile2 小时前
“自迭代” Skill 的 team-pitfalls 的演进
前端·后端·ai编程
林恒smileZAZ2 小时前
`Array(100).map(() => 1)` 为什么全为空?
前端·javascript
小巧的砖头2 小时前
C#会重蹈覆辙吗?系列之2:反射及元数据的性能问题
开发语言·前端·c#
KaMeidebaby2 小时前
卡梅德生物技术快报|蛋白的叠氮基修饰:实操解析:核酸模板耦合蛋白的叠氮基修饰实现靶蛋白定点共价标记
前端·人工智能·物联网·算法·百度
濮水大叔3 小时前
在大型 Vue 项目中,如何有效管理复杂的状态?“散装版” vs “套装版”
前端·vue.js·typescript
玄星啊3 小时前
可修改:代码的生存底线
前端·ai编程
没落英雄3 小时前
3. DeepAgents 实战 - Memory Skills 与上下文工程
前端·人工智能·架构