fix integer/float errors in survey

This commit is contained in:
Keith Grant 2020-10-20 10:29:23 -07:00
parent 44776189de
commit acd8a8dd3c
3 changed files with 41 additions and 1 deletions

View File

@ -18,6 +18,8 @@ import {
noWhiteSpace,
combine,
maxLength,
integer,
number as numberValidator,
} from '../../../util/validators';
function AnswerTypeField({ i18n }) {
@ -177,7 +179,15 @@ function SurveyQuestionForm({
<FormField
id="question-default"
name="default"
validate={maxLength(formik.values.max, i18n)}
validate={
{
text: maxLength(formik.values.max, i18n),
integer: integer(i18n),
float: numberValidator(i18n),
}[formik.values.type]
}
min={formik.values.min}
max={formik.values.max}
type={formik.values.type === 'text' ? 'text' : 'number'}
label={i18n._(t`Default answer`)}
/>

View File

@ -68,6 +68,7 @@ export function noWhiteSpace(i18n) {
export function integer(i18n) {
return value => {
console.log(value);
const str = String(value);
if (/[^0-9]/.test(str)) {
return i18n._(t`This field must be an integer`);
@ -76,6 +77,16 @@ export function integer(i18n) {
};
}
export function number(i18n) {
return value => {
const str = String(value);
if (/^[0-9]*(\.[0-9]*)?$/.test(str)) {
return undefined;
}
return i18n._(t`This field must be a number`);
};
}
export function url(i18n) {
return value => {
if (!value) {

View File

@ -4,6 +4,7 @@ import {
maxLength,
noWhiteSpace,
integer,
number,
url,
combine,
regExp,
@ -112,6 +113,24 @@ describe('validators', () => {
});
});
test('number should accept number (number)', () => {
expect(number(i18n)(13)).toBeUndefined();
});
test('number should accept number (string)', () => {
expect(number(i18n)('13')).toBeUndefined();
});
test('number should accept decimal/float', () => {
expect(number(i18n)(13.1)).toBeUndefined();
});
test('number should reject string containing alphanum', () => {
expect(number(i18n)('15a')).toEqual({
id: 'This field must be a number',
});
});
test('url should reject incomplete url', () => {
expect(url(i18n)('abcd')).toEqual({
id: 'Please enter a valid URL',