JavaSE-使用注解完成表单验证功能

根据上一篇文章讲过的注解留下来的题目,实现功能是利用注解完成一个表单验证功能,验证一个用户名字段。字段上有三个参数,分别为minLength、maxLength、keyWord,且必须满足几个条件:
a). 用户名长度是否>=minLength
b). 用户名长度是否<=maxLength
c). 用户名中是否包含keyWord关键字
d). 大写字母、小写字母、数字必须选至少2个。

用户实体类:

public class User {
@NameAnnotation()
    private String name;//定义一个字段:用户名

}

用户名字段注解:

import java.lang.annotation.*;

@Target({ElementType.TYPE , ElementType.METHOD,ElementType.FIELD })
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
public @interface NameAnnotation {
    int minLength() default 6;//默认为6
    int maxLength() default 12;//默认为12
    String keyWord() default "one";//默认关键字为one
}

测试类:

import java.lang.reflect.Field;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class TestUser {
    public static void main(String[] args) throws Exception {
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入你的用户名:");
        String name = sc.next();
        //获取name属性
        Class clazz = User.class;
        Field nameField = clazz.getDeclaredField("name");
        //获取属性的对应注解
        NameAnnotation annotation = nameField.getDeclaredAnnotation(NameAnnotation.class);
        String keyWord = annotation.keyWord();
        int max = annotation.maxLength();
        int min = annotation.minLength();
        int length = name.toCharArray().length;
        int length1=name.length();
        System.out.println(max);
        System.out.println(min);
        System.out.println(length);
        System.out.println(length1);
        //用户名中包含关键字,就返回true,没有就返回false
        Pattern pattern = Pattern.compile(keyWord);
        Matcher match = pattern.matcher(name);
        boolean b = match.find();
        if(length>max){
            System.out.println("注册用户名长度最大为"+max);
            return;
        }
        if(length<min){
            System.out.println("注册用户名长度至少为"+min);
            return;
        }
       if(!b){
            System.out.println("注册用户必须包含关键字:"+keyWord);
            return;
        }
         /*if(!name.contains(keyWord)){
            System.out.println("注册用户必须包含关键字:"+keyWord);
            return;
        }*/
        //也可以使用这个方式
        int count=0;
        if(name.matches(".*[a-z].*")){
            count++;
        }
        if(name.matches(".*[A-Z].*")){
            count++;
        }
        if(name.matches(".*[/d].*")){
            count++;
        }
        if(count<2){
            System.out.println("注册用户名必须大写字母、小写字母、数字必须选至少2个");
            return ;
        }
        System.out.println("注册用户名合法");

    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值