BAEL-112 - custom validator - format fixes

This commit is contained in:
slavisa-baeldung 2017-03-18 09:20:33 +00:00
parent f8bd663f7d
commit 42f1ef0bf3
4 changed files with 25 additions and 18 deletions

View File

@ -11,12 +11,14 @@ import javax.validation.Payload;
@Documented
@Constraint(validatedBy = ContactNumberValidator.class)
@Target( { ElementType.METHOD, ElementType.FIELD })
@Target({ElementType.METHOD, ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
public @interface ContactNumberConstraint {
String message() default "Invalid phone number";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}

View File

@ -6,14 +6,15 @@ import javax.validation.ConstraintValidatorContext;
public class ContactNumberValidator implements ConstraintValidator<ContactNumberConstraint, String> {
@Override
public void initialize(ContactNumberConstraint contactNumber) {}
public void initialize(ContactNumberConstraint contactNumber) {
}
@Override
public boolean isValid(String contactField, ConstraintValidatorContext cxt) {
if(contactField == null) {
if (contactField == null) {
return false;
}
return contactField.matches("[0-9]+") && (contactField.length() > 8) && (contactField.length() < 14);
return contactField.matches("[0-9]+") && (contactField.length() > 8) && (contactField.length() < 14);
}
}

View File

@ -3,7 +3,7 @@ package com.baeldung.model;
import com.baeldung.customvalidator.ContactNumberConstraint;
public class ValidatedPhone {
@ContactNumberConstraint
private String phone;
@ -15,4 +15,8 @@ public class ValidatedPhone {
this.phone = phone;
}
@Override
public String toString() {
return phone;
}
}

View File

@ -15,21 +15,21 @@ import com.baeldung.model.ValidatedPhone;
@EnableWebMvc
public class ValidatedPhoneController {
@RequestMapping(value="/validatePhone", method=RequestMethod.GET)
@RequestMapping(value = "/validatePhone", method = RequestMethod.GET)
public String loadFormPage(Model m) {
m.addAttribute("validatedPhone", new ValidatedPhone());
return "phoneHome";
m.addAttribute("validatedPhone", new ValidatedPhone());
return "phoneHome";
}
@RequestMapping(value="/addValidatePhone", method=RequestMethod.POST)
@RequestMapping(value = "/addValidatePhone", method = RequestMethod.POST)
public String submitForm(@Valid ValidatedPhone validatedPhone, BindingResult result, Model m) {
if(result.hasErrors()) {
return "phoneHome";
}
m.addAttribute("message", "Successfully saved phone: " + validatedPhone.toString());
if (result.hasErrors()) {
return "phoneHome";
}
m.addAttribute("message", "Successfully saved phone: " + validatedPhone.toString());
return "phoneHome";
}
}