UNPKG

lumen-react-javascript

Version:
65 lines (54 loc) 1.61 kB
import {defineMessages} from 'react-intl'; import {AbstractValidatorRule} from './abstract-validator-rule'; export interface NumberValidatorRuleOptions { strict?: boolean; integer?: boolean; min?: number; max?: number; } export class NumberValidatorRule extends AbstractValidatorRule { private options: NumberValidatorRuleOptions = { strict: false, integer: false, }; public constructor(options?: NumberValidatorRuleOptions) { super(); if (options) { this.options = options; } } protected getDefaultMessage(): ReactIntl.FormattedMessage.MessageDescriptor { return defineMessages({ error: { id: 'validator.invalidNumber', defaultMessage: 'Should be a valid number.', } }).error; } public isValid(value): boolean { if (typeof value === "string") { if (this.options.strict) { return false; } else if (!value.match(/[0-9]*(?=\.[0-9]*)?/)) { return false; } value = parseFloat(value); } if (this.options.integer) { if (Math.round(value) !== value) { return false; } } if (this.options.min !== undefined) { if (value < this.options.min) { return false; } } if (this.options.max !== undefined) { if (value > this.options.max) { return false; } } return true; } }