问题描述
我正在 pythonanywhere.com 中开发 web2py - 模型 - db_testing.py
以下代码运行成功:
# -*- coding: utf-8 -*-
db = DAL('sqlite://storage.sqlite')
db.define_table('registration',Field('firstname',requires=IS_NOT_EMPTY(error_message='Should not left blank')),Field('lastname',requires=IS_NOT_EMPTY()),Field('gender',requires=IS_IN_SET(['Male','Female'])),Field('birthday','date'),Field('email',requires = IS_EMAIL(error_message='invalid email!')),Field('salary','integer'),Field('seniority','integer')
)
然而,第一个字段'firstname'只能防止表单填写而不是留空。它无法验证输入是在 a-z 或 A-Z 中。
最后一个字段'seniority'可以保证表单填写必须是0-9,但不能阻止表单填写不留空。
如何设置这两个要求(带有 error_message 的 IS_NOT_EMPTY 并确保输入是字符串/整数)?
有什么想法吗?
解决方法
如 documentation 中所述,import React,{useEffect,useState} from 'react';
import {View,StyleSheet} from 'react-native';
import {Picker} from '@react-native-picker/picker';
import AsyncStorage from '@react-native-community/async-storage';
const ProductPicker = () => {
const [selectedValue,setSelectedValue] = useState('');
const [productDetails,setproductDetails] = useState([]);
useEffect(() => {
getProductList();
},[]);
const getProductList = async () => {
const token = await AsyncStorage.getItem('userToken');
fetch("http://10.0.2.2:3000/customer/get-all-products",{
method: "post",headers: {
'Content-Type': 'application/json','Authentication': `Bearer ${token}`
},})
.then((response) => response.json())
.then((json) => setproductDetails(json.data))
.catch((error) => console.error(error))
};
const renderProductList = () => {
return productDetails.map((product) => {
return <Picker.item label={product.productName} value={product} />
})
}
return (
<View style={styles.container}>
<Picker
selectedValue={selectedValue}
style={{height: 40,width: 150}}
onValueChange={(itemValue,itemIndex) => {
setSelectedValue(itemValue);
}}
>
{renderProductList()}
</Picker>
</View>
);
};
const styles = StyleSheet.create({
container: {
flex: 1,paddingTop: 40,alignItems: 'center',},});
export default ProductPicker;
的 requires
属性可以是验证器列表。所以,你可以这样做:
Field
要限制为仅使用字母,请将 Field('firstname',requires=[IS_NOT_EMPTY(),IS_ALPHANUMERIC()])
与正则表达式一起使用:
IS_MATCH
以上,您不一定需要 Field('firstname',IS_MATCH('^[a-zA-Z]+$')])
验证器,因为 IS_NOT_EMPTY
中的正则表达式需要至少一个字母,但您可能希望保留 IS_MATCH
以显示一个专门针对空响应的不同错误消息。
检查是否是字符串:if isinstance(firstname,str)
检查是否非空:可以执行if firstname != ''
或if firstname
;在 Python 中,当用作布尔值时,空对象被视为“假”。要检查它是否是字母字符,您可以执行if firstname.isalpha()
。