Monday, 5 April 2021

Bean Validation: NegativeOrZero: Number must be negative or zero

If you apply @NegativeOrZero annotation on a number, then the annotated number must be a negative number or zero.

 

Example

@NegativeOrZero

private int y;

 

Supported Types

a.   BigDecimal

b.   BigInteger

c.    byte

d.   short

e.   int

f.     long

 

Where can I apply this annotation?

a.   METHOD

b.   FIELD

c.    ANNOTATION_TYPE

d.   CONSTRUCTOR

e.   PARAMETER

f.     TYPE_USE

 

Coordinates.java

package com.sample.app.model;

import javax.validation.constraints.Negative;
import javax.validation.constraints.NegativeOrZero;

public class Coordinates {
	@Negative
	private int x;

	@NegativeOrZero
	private int y;

	public Coordinates(@Negative int x, @NegativeOrZero int y) {
		super();
		this.x = x;
		this.y = y;
	}

	public int getX() {
		return x;
	}

	public void setX(int x) {
		this.x = x;
	}

	public int getY() {
		return y;
	}

	public void setY(int y) {
		this.y = y;
	}

}

 

App.java

package com.sample.app;

import java.util.Set;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;

import com.sample.app.model.Coordinates;

public class App {
	private static ValidatorFactory validatorFactory = Validation.buildDefaultValidatorFactory();
	private static Validator validator = validatorFactory.getValidator();

	private static void validateBean(Coordinates coordinates) {
		System.out.println("************************************");
		Set<ConstraintViolation<Coordinates>> validationErrors = validator.validate(coordinates);

		if (validationErrors.size() == 0) {
			System.out.println("No validation errors....");
		}

		for (ConstraintViolation<Coordinates> violation : validationErrors) {
			System.out.println(violation.getPropertyPath() + "," + violation.getMessage());
		}
		System.out.println("");
	}

	public static void main(String args[]) {
		Coordinates positiveCoordinates = new Coordinates(10, 20);

		System.out.println("Validation errors on bean positiveCoordinates");
		validateBean(positiveCoordinates);

		Coordinates negativeCoordinates = new Coordinates(-10, -20);

		System.out.println("Validation errors on bean negativeCoordinates");
		validateBean(negativeCoordinates);

	}
}

 

Output

Validation errors on bean positiveCoordinates
************************************
x,must be less than 0
y,must be less than or equal to 0

Validation errors on bean negativeCoordinates
************************************
No validation errors....

 

 

 

 

  

Previous                                                    Next                                                    Home

No comments:

Post a Comment