Home > Java > javaTutorial > Java implements verification and formatting of form fields

Java implements verification and formatting of form fields

王林
Release: 2023-08-09 17:41:10
Original
1646 people have browsed it

Java implements verification and formatting of form fields

Java implements form field verification and formatting

In web development, forms are a frequently used interaction method. The field verification and formatting of the form are important links to ensure the legality and consistency of the data. In Java, we can use various methods to verify and format form fields.

1. Regular expression verification

Regular expression is a powerful string matching tool that can match target strings according to certain rules. In form field validation, we can use regular expressions to verify whether the input content conforms to the specified format.

For example, we can use regular expressions to verify whether the email address complies with the specification:

String emailPattern = "\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*";
String email = "example@example.com";

if (email.matches(emailPattern)) {
    System.out.println("邮箱地址格式正确");
} else {
    System.out.println("邮箱地址格式不正确");
}
Copy after login

In the above code, we define a regular expression pattern and then use matches() Method to check if the entered email address matches the pattern.

2. Use Java’s own verification tool classes

Java provides some built-in verification tool classes that can help us quickly verify form fields. The most commonly used one is the annotation verification in the javax.validation package.

We can verify the form by adding corresponding annotations to the fields, for example:

import javax.validation.constraints.*;

public class User {

    @NotNull(message = "用户名不能为空")
    @Size(min = 6, max = 20, message = "用户名长度应在6到20个字符之间")
    private String username;

    @NotEmpty(message = "密码不能为空")
    @Pattern(regexp = "^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%^&+=])(?=\S+$).{8,}$",
        message = "密码必须包含大小写字母、数字和特殊字符,并且长度至少为8位")
    private String password;

    // 省略getter和setter方法
}
Copy after login

In the above code, we use some commonly used annotation verification, such as @ NotNull indicates that the field cannot be null, @Size limits the length range of the field, @NotEmpty indicates that the field cannot be empty, and @Pattern uses regular expressions to verify the format of the field, etc.

Then we can use the validator in Java to verify the User object:

import javax.validation.*;

public class Main {

    public static void main(String[] args) {
        User user = new User();
        user.setUsername("admin");
        user.setPassword("123456");

        ValidatorFactory validatorFactory = Validation.buildDefaultValidatorFactory();
        Validator validator = validatorFactory.getValidator();
        Set<ConstraintViolation<User>> violations = validator.validate(user);

        for (ConstraintViolation<User> violation : violations) {
            System.out.println(violation.getMessage());
        }
    }
}
Copy after login

In the above code, we first create a User object, and then use the Validation class The buildDefaultValidatorFactory() method obtains a validator factory object, and then obtains the validator through the factory object. Finally, use the validator to verify the User object and print out information that violates the verification rules.

3. Field formatting

In addition to verification, sometimes we also need to format the form fields, such as formatting the mobile phone number into the form of xxx-xxxx-xxxx, or The date is formatted in the form of yyyy-MM-dd, etc.

In Java, we can use the SimpleDateFormat class to format dates, for example:

import java.text.*;
import java.util.*;

public class Main {

    public static void main(String[] args) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        Date date = new Date();
        String formattedDate = format.format(date);
        System.out.println(formattedDate);
    }
}
Copy after login

In the above code, we create a date formatting object through the SimpleDateFormat class, Then call the format() method to format the date object into the specified string format.

For other types of fields, we can use some string processing methods to format, such as using the substring() method to separate mobile phone numbers:

String phoneNumber = "15812345678";
String formattedNumber = phoneNumber.substring(0, 3) + "-" +
                        phoneNumber.substring(3, 7) + "-" +
                        phoneNumber.substring(7, 11);
System.out.println(formattedNumber);
Copy after login

In the above code, We used the substring() method to separate the mobile phone numbers according to the specified format.

Through the above examples, we can see that Java provides a variety of methods to verify and format form fields. Based on actual needs, choosing an appropriate method can simplify development and improve efficiency. In practical applications, we can also combine front-end validation and back-end validation to ensure the security and correctness of form input.

The above is the detailed content of Java implements verification and formatting of form fields. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template