blob: c5088eef2fb8b2c2ca2c00cd4aa87ac1f3f75e66 [file] [log] [blame]
/*=============================================================================#
# Copyright (c) 2007, 2021 Stephan Wahlbrink and others.
#
# This program and the accompanying materials are made available under the
# terms of the Eclipse Public License 2.0 which is available at
# https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0
# which is available at https://www.apache.org/licenses/LICENSE-2.0.
#
# SPDX-License-Identifier: EPL-2.0 OR Apache-2.0
#
# Contributors:
# Stephan Wahlbrink <sw@wahlbrink.eu> - initial API and implementation
#=============================================================================*/
package org.eclipse.statet.ecommons.databinding.core.validation;
import java.text.ParsePosition;
import com.ibm.icu.text.NumberFormat;
import org.eclipse.core.databinding.validation.IValidator;
import org.eclipse.core.databinding.validation.ValidationStatus;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.statet.jcommons.lang.NonNullByDefault;
/**
* Validator for decimals.
*/
@NonNullByDefault
public class DecimalValidator implements IValidator<Object> {
private final NumberFormat formatter;
private final boolean allowEmpty;
private final double min;
private final double max;
private final String message;
public DecimalValidator(final double min, final double max, final boolean allowEmpty,
final String message) {
this.allowEmpty= allowEmpty;
this.min= min;
this.max= max;
this.message= message;
this.formatter= NumberFormat.getNumberInstance();
this.formatter.setParseIntegerOnly(false);
}
public DecimalValidator(final double min, final double max,
final String message) {
this(min, max, false, message);
}
@Override
public IStatus validate(final Object value) {
if (value instanceof String) {
final String s= ((String)value).trim();
if (this.allowEmpty && s.length() == 0) {
return Status.OK_STATUS;
}
final ParsePosition result= new ParsePosition(0);
final Number number= this.formatter.parse(s, result);
if (result.getIndex() == s.length() && result.getErrorIndex() < 0) {
final double n= number.doubleValue();
if (n >= this.min && n <= this.max) {
return Status.OK_STATUS;
}
// return range message
}
}
return ValidationStatus.error(this.message);
}
}