1

I made a registration form and I want to validate all filed of the form I validated expect one field to match the fields of PASSWORD matching so make custom validtion but is not working i attaced code in

@Entity
public class Userlist {
  ......
  @Size(min = 8, message = "Please enter atleast 8 digit password")
  private String userpassword;
  @PasswordMatch(message="Your Password is not match with created password")
  private String confirmpassword;
}


package com.picture.picturesalbum.anotation;

import static java.lang.annotation.ElementType.ANNOTATION_TYPE;  
import static java.lang.annotation.ElementType.CONSTRUCTOR;
import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.ElementType.PARAMETER;
import static java.lang.annotation.ElementType.TYPE_USE;

import java.lang.annotation.*;

import jakarta.validation.Constraint;
import jakarta.validation.Payload;

@Target({ METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER, TYPE_USE })
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Constraint(validatedBy = PasswordMatchValidator.class)
public @interface PasswordMatch {

public String message() default "Your Password is not match with created password ";
public Class<?>[] groups() default {};
public Class<? extends Payload>[] payload() default {};

}


  package com.picture.picturesalbum.anotation;
  import com.picture.picturesalbum.model.Userlist;
  import jakarta.validation.ConstraintValidator; 
  import jakarta.validation.ConstraintValidatorContext;
  public class PasswordMatchValidator implements ConstraintValidator<PasswordMatch, String> {
  Userlist userlist = new Userlist();
  public boolean isValid(String value, ConstraintValidatorContext context) {
 // Userlist userlist = new Userlist(); 
    if (value.contentEquals(userlist.getUserpassword())) {
        return true;
    } else {
        return false;
    }
  }
}

Error is

    at java.base/java.lang.Thread.run(Thread.java:1589)

Caused by: java.lang.NullPointerException: Cannot invoke "java.lang.CharSequence.length()" because "cs" is null

1 Answers1

0

If you want to validate two fields of a class, you have to use a custom validator with a class level constraint and then compare both values in the validator class.

Check this answer for more information.

Another solution is to define a method that must validate to true and put the @AssertTrue annotation on the top of it:

@AssertTrue
private boolean isEqual() {
    return userpassword.equals(confirmPassword);
}
toowboga
  • 116
  • 1
  • 6