当前位置: 首页 > news >正文

正则表达式使用示例

下面以 Vue(前端)和 Spring Boot(后端)为例,展示正则表达式在前后端交互中的应用,以邮箱格式验证为场景:

1.前端

<template><div class="register-container"><h3>用户注册</h3><form @submit.prevent="handleSubmit"><div class="form-group"><label>邮箱:</label><input type="text" v-model="email" @input="validateEmail"placeholder="请输入邮箱"><p class="error-message" v-if="!isEmailValid && email.length > 0">请输入有效的邮箱格式(如:example@domain.com)</p></div><button type="submit" :disabled="!isEmailValid">注册</button></form></div>
</template><script setup>
import { ref, computed } from 'vue';
import axios from 'axios';// 响应式数据
const email = ref('');// 邮箱正则表达式(与后端保持一致)
const emailReg = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;// 验证状态
const isEmailValid = computed(() => {return emailReg.test(email.value);
});// 实时验证(可选,也可依赖computed自动响应)
const validateEmail = () => {// 可在这里添加更复杂的验证逻辑
};// 提交表单
const handleSubmit = async () => {try {const response = await axios.post('/api/register', { email: email.value });alert(response.data.message);} catch (error) {alert(error.response?.data?.message || '注册失败');}
};
</script><style scoped>
.register-container {max-width: 400px;margin: 20px auto;padding: 20px;border: 1px solid #ddd;border-radius: 4px;
}.form-group {margin-bottom: 15px;
}input {width: 100%;padding: 8px;margin-top: 5px;border: 1px solid #ddd;border-radius: 4px;
}.error-message {color: #ff4444;font-size: 12px;margin: 5px 0 0 0;
}button {padding: 8px 16px;background-color: #007bff;color: white;border: none;border-radius: 4px;cursor: pointer;
}button:disabled {background-color: #cccccc;cursor: not-allowed;
}
</style>

2.后端

import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;import jakarta.validation.Valid;
import jakarta.validation.constraints.Pattern;@RestController
@RequestMapping("/api")
@Validated // 开启方法参数验证
public class UserController {// 邮箱正则表达式(与前端保持一致)private static final String EMAIL_REGEX = "^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$";@PostMapping("/register")public ResponseEntity<Result> register(@Valid @RequestBody RegisterRequest request) {// 验证通过:执行注册逻辑(如存入数据库)return ResponseEntity.ok(new Result(true, "邮箱 " + request.getEmail() + " 格式验证通过,注册成功!"));}// 请求参数封装类public static class RegisterRequest {@Pattern(regexp = EMAIL_REGEX,message = "邮箱格式无效,请重新输入")private String email;// getter和setterpublic String getEmail() {return email;}public void setEmail(String email) {this.email = email;}}// 响应结果封装类public static class Result {private boolean success;private String message;public Result(boolean success, String message) {this.success = success;this.message = message;}// getter和setterpublic boolean isSuccess() {return success;}public void setSuccess(boolean success) {this.success = success;}public String getMessage() {return message;}public void setMessage(String message) {this.message = message;}}
}

3.小结

前端验证逻辑

  • 使用 Vue 的响应式数据email绑定输入框
  • 通过计算属性isEmailValid实时判断格式是否正确
  • 提交按钮状态随验证结果动态禁用 / 启用
  • 用 Axios 发送 POST 请求到后端接口

后端验证逻辑

  • 使用@Pattern注解在RegisterRequest类中定义邮箱正则规则
  • 添加@Valid注解触发参数验证
  • 验证失败时,Spring 会自动返回 400 错误和自定义提示信息
  • 验证通过后执行实际注册逻辑

文章转载自:
http://angiomatous.wanhuigw.com
http://achromatic.wanhuigw.com
http://calculational.wanhuigw.com
http://autocycle.wanhuigw.com
http://bight.wanhuigw.com
http://chevalet.wanhuigw.com
http://awedly.wanhuigw.com
http://chestnutting.wanhuigw.com
http://brooklet.wanhuigw.com
http://brave.wanhuigw.com
http://aloeswood.wanhuigw.com
http://canonic.wanhuigw.com
http://beograd.wanhuigw.com
http://chawl.wanhuigw.com
http://badmash.wanhuigw.com
http://admass.wanhuigw.com
http://alcoholic.wanhuigw.com
http://aerobomb.wanhuigw.com
http://audaciously.wanhuigw.com
http://anime.wanhuigw.com
http://catechesis.wanhuigw.com
http://chromite.wanhuigw.com
http://addition.wanhuigw.com
http://canon.wanhuigw.com
http://anginal.wanhuigw.com
http://astylar.wanhuigw.com
http://bromide.wanhuigw.com
http://arlington.wanhuigw.com
http://bullring.wanhuigw.com
http://absorptivity.wanhuigw.com
http://www.dtcms.com/a/280536.html

相关文章:

  • 【canal+mysql+example+数据验证测试】
  • 从 0 到 1 掌握 自研企业级分布式 ID 发号器
  • C 语言(二)
  • GaussDB 数据库架构师修炼(三) 集群管理概览
  • Kafka 4.0 技术深度解析
  • 现代CSS实战:用变量与嵌套重构可维护的前端样式
  • Go 错误处理全解析:从 error 到 panic
  • Go 包管理工具详解:安装与使用指南
  • 【轨物方案】当补贴退潮,光伏电站如何回归价值本质?
  • 上公网-从内网到公网
  • 李宏毅《生成式人工智能导论》 | 第9讲 AI Agent
  • 本地电脑安装Dify|内网穿透到公网
  • 1.1 前端-vue3项目的创建
  • JS基础知识(下)
  • docker容器、宿主机、cpu核数关系
  • c# sqlsugar 主子表明细 查询
  • C语言操作符补充
  • linux系统------HAProxy 配置
  • 酷淘商场项目【从零到一详解】Web端抓包操作与测试报告(二)
  • 部署项目将dll放到system32?不可取
  • Ubuntu环境下的K3S集群搭建
  • 【如何理解SerializedProperty】
  • 【项目】-番茄时钟设计
  • 云手机隐私保护指南:如何保障账号与数据的云端安全?
  • 编程技能:多文件编译
  • 本地 LLM API Python 项目分步指南
  • 20250715给荣品RD-RK3588开发板刷Android14时打开USB鼠标
  • Android 获取 UserAgent (UA) 的三种方式深度解析:差异、风险与最佳实践
  • Hystrix与Resilience4j在微服务熔断降级中的应用对比与实战
  • 用 K-means 算法实现水果分堆