te')); return $arr; } /* 遍历用户所有主题 * @param $uid 用户ID * @param int $page 页数 * @param int $pagesize 每页记录条数 * @param bool $desc 排序方式 TRUE降序 FALSE升序 * @param string $key 返回的数组用那一列的值作为 key * @param array $col 查询哪些列 */ function thread_tid_find_by_uid($uid, $page = 1, $pagesize = 1000, $desc = TRUE, $key = 'tid', $col = array()) { if (empty($uid)) return array(); $orderby = TRUE == $desc ? -1 : 1; $arr = thread_tid__find($cond = array('uid' => $uid), array('tid' => $orderby), $page, $pagesize, $key, $col); return $arr; } // 遍历栏目下tid 支持数组 $fid = array(1,2,3) function thread_tid_find_by_fid($fid, $page = 1, $pagesize = 1000, $desc = TRUE) { if (empty($fid)) return array(); $orderby = TRUE == $desc ? -1 : 1; $arr = thread_tid__find($cond = array('fid' => $fid), array('tid' => $orderby), $page, $pagesize, 'tid', array('tid', 'verify_date')); return $arr; } function thread_tid_delete($tid) { if (empty($tid)) return FALSE; $r = thread_tid__delete(array('tid' => $tid)); return $r; } function thread_tid_count() { $n = thread_tid__count(); return $n; } // 统计用户主题数 大数量下严谨使用非主键统计 function thread_uid_count($uid) { $n = thread_tid__count(array('uid' => $uid)); return $n; } // 统计栏目主题数 大数量下严谨使用非主键统计 function thread_fid_count($fid) { $n = thread_tid__count(array('fid' => $fid)); return $n; } ?>javascript - Formik input value for a number becomes a string even after it passes the Formik validation as a number - Stack Ove
最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Formik input value for a number becomes a string even after it passes the Formik validation as a number - Stack Ove

programmeradmin3浏览0评论

I have an input through Formik that takes in number, but even when it passes the Formik validation, the resulting input is still categorized as string.

                <Formik
                    initialValues={{ price: '' }}
                    onSubmit={submitHandler}
                    validationSchema={yup.object().shape({
                    price: yup
                        .number()
                        .required(),
                    })}
                >
                    {({ values, handleChange, errors, setFieldTouched, touched, isValid, handleSubmit }) => (
                        <View style={styles.form}>
                            <View style={styles.fieldset}>
                                <Text style={{ marginLeft: 40, marginVertical: 10 }}>
                                    <Text style={{ color: '#FF5D4E'}}>* </Text>
                                    Price
                                </Text>
                                <TextInput
                                    value={values.price}
                                    keyboardType = 'numeric'
                                    onChangeText={handleChange('price')}
                                    placeholder="Rental price of your item per day"
                                    style={styles.textInput}
                                    onBlur={() => setFieldTouched('price')}
                                />
                            </View>
                            {touched.price && errors.price &&
                                <Text style={{ fontSize: 10, color: 'red' }}>{errors.price}</Text>
                            }

                            <TouchableOpacity
                                disabled={!isValid || loading}
                                onPress={handleSubmit}
                                style={styles.button}
                            >
                                <Text style={styles.buttonText}>Submit</Text>
                            </TouchableOpacity> 
                        </View> 
                    )}
                </Formik> 

When the price is entered, any non-number is met with a warning. However, when I console log the the value passed to the submitHandler function, the typeof shows the price value as a string.

I have an input through Formik that takes in number, but even when it passes the Formik validation, the resulting input is still categorized as string.

                <Formik
                    initialValues={{ price: '' }}
                    onSubmit={submitHandler}
                    validationSchema={yup.object().shape({
                    price: yup
                        .number()
                        .required(),
                    })}
                >
                    {({ values, handleChange, errors, setFieldTouched, touched, isValid, handleSubmit }) => (
                        <View style={styles.form}>
                            <View style={styles.fieldset}>
                                <Text style={{ marginLeft: 40, marginVertical: 10 }}>
                                    <Text style={{ color: '#FF5D4E'}}>* </Text>
                                    Price
                                </Text>
                                <TextInput
                                    value={values.price}
                                    keyboardType = 'numeric'
                                    onChangeText={handleChange('price')}
                                    placeholder="Rental price of your item per day"
                                    style={styles.textInput}
                                    onBlur={() => setFieldTouched('price')}
                                />
                            </View>
                            {touched.price && errors.price &&
                                <Text style={{ fontSize: 10, color: 'red' }}>{errors.price}</Text>
                            }

                            <TouchableOpacity
                                disabled={!isValid || loading}
                                onPress={handleSubmit}
                                style={styles.button}
                            >
                                <Text style={styles.buttonText}>Submit</Text>
                            </TouchableOpacity> 
                        </View> 
                    )}
                </Formik> 

When the price is entered, any non-number is met with a warning. However, when I console log the the value passed to the submitHandler function, the typeof shows the price value as a string.

Share Improve this question asked Nov 21, 2019 at 23:08 KevvvKevvv 4,02312 gold badges52 silver badges105 bronze badges 3
  • 2 I've never use yup, but in joi just using number() doesn't control the type but only the content. Try adding .strict() to the validation – Auticcat Commented Nov 22, 2019 at 11:18
  • @Auticcat What's the difference between the type and content? – Kevvv Commented Nov 22, 2019 at 18:23
  • For example number = 1 has content equal to 1 but has as type number. If you do number = “1” has content equal to 1 like before, but is a string. Doing strict will control that the content is a number but also control that the type is equal to number – Auticcat Commented Nov 22, 2019 at 18:26
Add a ment  | 

2 Answers 2

Reset to default 6

This is just happening while using Formik with React Native. In React for web you can set the input with type="number" but in React Native you can't.

Even if you add keyboardType="numeric" to <TextInput />. In the other hand, if you use Yup (which I strongly remend) this is not checking for type, just for content this means "1" may be interpreted as a number.

Solution:

import Formik from 'formik';
import * as yup from 'yup';

...

<Formik 
  initialValues={{ price: '' }}
  validationSchema={yup.object().shape({ price: yup.number() })}
/>
{(values, setFieldValue, handleBlur) => (
  <TextInput 
    value={values.price} 
    onChangeText={value => setFieldValue('price', parseFloat(value))}
    onBlur={handleBlur('price')}
    keyboardType="decimal-pad"
  />
)}
</Formik>

happy coding!

You can parse the string value in onChangeText like this:


{({ values, ...., setFieldValue }) => {

// parse string value to int
const parseAndHandleChange = (value, setFieldValue, id) => {
      const parsed = parseInt(value, 10)
      setFieldValue(id, parsed)
    }

return (
 <View>
 {.....}
 <TextInput
   value={values.price}
   keyboardType = 'numeric'
   onChangeText={value => parseAndHandleChange(value, setFieldValue, 'price')}
   placeholder="Rental price of your item per day"
   style={styles.textInput}
   onBlur={() => setFieldTouched('price')}
 />
 </View>
)}

This is just an example, feel free to modify based on your use case. Hope it helps.

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论