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

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

相关推荐
Embrace9245 分钟前
React Native + Realm 离线方案处理
javascript·react native·react.js·realm
chenyingjian15 分钟前
鸿蒙|能力特性-统一文件预览
前端·harmonyos
毛骗导演16 分钟前
OpenClaw 沙箱执行系统深度解析:一条 exec 命令背后的安全长城
前端·架构
天才聪22 分钟前
鸿蒙开发vs前端开发1-父子组件传值
前端
卡尔特斯24 分钟前
Android Studio 代理配置指南
android·前端·android studio
李剑一29 分钟前
同样做缩略图,为什么别人又快又稳?踩过无数坑后,我总结出前端缩略图实战指南
前端·vue.js
Jolyne_41 分钟前
Taro样式重构记录
前端
恋猫de小郭1 小时前
Google 开源大模型 Gemma4 怎么选,本地跑的话需要什么条件?
前端·人工智能·ai编程
文心快码BaiduComate1 小时前
Comate搭载GLM-5.1:长程8H,对齐Opus 4.6
前端·后端·架构
熊猫钓鱼>_>1 小时前
AI驱动的Web应用智能化:WebMCP、WebSkills与WebAgent的融合实践
前端·人工智能·ai·skill·webagent·webmcp·webskills