简体   繁体   中英

Java Bean validation and regex - format and length in two different error message

For example, input is phone number. Format is

(country code)(space)(area code)(space)(phone number)

Area code can be blank.

e.g.
63 240 1234567   (valid)
63 1234567  (valid)

What regex pattern do I need so I can have it check if all characters are numeric and if the phone number (without country and area code) is of a certain length?

and is it possible that using only one pattern, I can have two distinct error messages for two distinct invalid input: 1. All characters should be numeric 2. Actual Phone number length should be 7 to 10.

because we currently have it this way

@Pattern(regexp=" some regex pattern", message="phone is invalid")
private String phoneNumber

I could add a @Size validator but I only need to trim out the phone number.

Can anyone help?

This expression could work:

^(\d{2})\s(?:(\d{3})\s)?(\d{7,10})$

Explanation:

  • ^ Begining of string
  • (\\d{2})\\s 2 digits, followed by a space (country code)(space)
  • (?:(\\d{3})\\s)? (optional) 3 digits, followed by a space (area code)(space)
  • (\\d{7,10}) 7 to 10 digits
  • $ End of string

Example

Limitations:

  • It will match things like 63 240 1234567 and 63 1234567 but it wouldn't match 631234567 or 63 240 1234567 , it's expecting a space after each of those sections. It's easy to work around those limitations, but it depends on the level of validation you require. If spaces are optional, you could replace both \\s by \\s?

Variant

If you want all the spaces and the country code to be optional, here's a variant: ^(?:(\\d{2})\\s?)?(?:(\\d{3})\\s?)?(\\d{7,10})$

Code Sample

If you would like to evaluate both patterns, in sequential order, you could go with this answer ( https://stackoverflow.com/a/41603564/7400458 ), for the Java code, combined with the two regex above.

 @GroupSequence({First.class, Second.class}) public interface Sequence {} @Size(min = 2, max = 10, message = "Name length improper", groups = { First.class }) @Pattern(regexp = "T.*", message = "Name doesn't start with T" , groups = { Second.class }) private String name; 

When now validating a Bean instance using the defined sequence (validator.validate(bean, Sequence.class)), at first the @Size constraint will be validated and only if that succeeds the @Pattern constraint.

Something like that:

 @GroupSequence({First.class, Second.class})
 public interface Sequence {}

 @Pattern(regexp = "^[ \d]+$", message = "Numeric input required" , groups = { First.class })
 @Pattern(regexp = "^(?:(\d{2})\s?)?(?:(\d{3})\s?)?(\d{7,10})$", message = "Phone no. should be 7-10 in length" , groups = { Second.class })
 private String phoneNumber;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM