有没有一种方法可以将文本输入限制在最小长度和最大长度之间。假设我想将textinput的长度限制在5到15之间,该怎么做?
答案 0 :(得分:2)
您可以按照以下步骤使用redux-form进行操作
we.js
module.exports = {
reqMsg: 'Required',
maxLength: max => value => value && value.length > max ? `Must be ${max} characters or less` : undefined,
minValue: min => value => value && value.length < min ? `Must be at least ${min} characters` : undefined,
};
validations.js
import { reqMsg, maxLength, minValue } from './we';
module.exports = {
//Validation
required: value => value ? undefined : reqMsg,
maxLength15: maxLength(15),
minValue5: minValue(5)
};
UserCreateForm.js
import React, { Component } from 'react';
import { Field, reduxForm } from 'redux-form';
import { Item, Input, CheckBox, ListItem, Spinner, Icon } from 'native-base';
import { required, minValue5, maxLength15} from './validations';
const renderField = ({ secureTextEntry, iconType, iconName, keyboardType, placeholder, meta: { touched, error, warning }, input: { onChange, ...restInput } }) => {
return (
<View>
<Item error={touched && !!error} rounded>
<Icon type={iconType} name={iconName} />
<Input secureTpickerStyleextEntry={JSON.parse(secureTextEntry)} keyboardType={keyboardType}
onChangeText={onChange} {...restInput} placeholder={placeholder} autoCapitalize='none'>
</Input>
{touched && !!error && <Icon name='close-circle' />}
</Item>
{touched && (!!error && <Text>{error}</Text>)}
</View>
);
};
class UserComponent extends Component {
render() {
return (
<Field name="Name" iconType="SimpleLineIcons" iconName="user" secureTextEntry="false" keyboardType="default" placeholder="FirstName LastName NikeName" component={renderField}
validate={[required, minValue5, maxLength15]}
/>
);
}
}
const UserCreateForm = reduxForm({
form: USER_CREATE_FORM // a unique identifier for this form
})(UserComponent);
export default UserCreateForm;
答案 1 :(得分:0)
考虑在您的组件中添加以下代码:
<TextInput onTextChange={this.onTextChange} maxLength={15} ... />
<Button onPress={this.onPress} ... >Submit</Button>
onTextChange = text => {
this.setState({text : text});
}
onPress = () => {
const {text} = this.state;
if(text.length < 5) {
console.log('Your text is less than what is required.');
}
}
答案 2 :(得分:0)
先前的评论也不错,但是它具有更多的时间和空间复杂性。为此,请使用此代码。
<TextInput onTextChange={this.onTextChange} maxLength={15} ... />
onTextChange=()=>{
if (value ==^[a-zA-Z0-9]{5,15}$) {
alert( "Input is valid\n");
} else {
alert( "Input is invalid\n");
}
}
此代码可帮助我使用此代码,也可以重置限制长度,更改值 这里5:-最小 15:-最大值。