当前位置: 首页 > 知识库问答 >
问题:

使用React本机从前端验证多个字段

孔深
2023-03-14

如何从前端验证所有的字段我这里有4个字段,我写了一个模糊的函数,我该如何进行呢

导入反应,{组件}从“反应”

类Signup扩展组件{

constructor(props) {
    super(props);
    this.state = {
        mobileno: '',
        email: '',
        password: '',
    }
}

hanldeValidation(text, type) {
    var mobilregex = /^[0-9]/;


    if (this.state.mobileno == '' && mobilregex.test(text) == false) {
        this.setState({
            errormobile: true
        })
    }

    else if (this.state.email == '' && emailregex.test(text) == false) {
        this.setState({
            erroremail: true
        })
    }
}






render() {

    return (
        <View>

            <Content style={{
                paddingLeft: 10,
                paddingRight: 10,
                backgroundColor: 'white'
            }}>

                <View style={{ paddingTop: 35, backgroundColor: '#ffffff', width: '100%', alignItems: 'center' }}>



                    {/*  Input Fields */}

                    <Item  >
                        <Input ref="mobileno" placeholder={strings('EnterMobileno')}
                            value={this.state.mobileno}
                            onChangeText={(mobileno) => this.setState({ mobileno: mobileno })}
                            onBlur={(mobileno) => this.hanldeValidation(mobileno, 'mobileno')}
                        />
                    </Item>
                    {
                        this.state.errormobile ?
                            <Text style={{ textAlign: 'center', color: 'red' }}>
                                {'Enter a valid number'}
                            </Text>
                            :
                            null
                    }



                    <Item >
                        <Input ref="email" placeholder={'Enter Email ( optional )'}
                            value={this.state.email}
                            onChangeText={(email) => this.setState({ email: email })}
                        />
                    </Item>

                    <Item >
                        <Input ref="password" placeholder={'Enter password'}
                            value={this.state.password}
                            onChangeText={(password) => this.setState({ password: password })}
                        />
                    </Item>



                    {/* Signup Button */}
                    <Button block rounded
                        style={styles.loginButtonStyle}
                        onPress={() => this.props.createUser(this.state)}
                    >
                        Signup
      </Button>

                </View>

            </Content>

        </View >
    )
}

}

const mapStateToProps =(state)= 1

}

const mapDispatchToProps=(调度)=

}

导出默认值(注册屏幕)

共有1个答案

葛驰
2023-03-14

您可以使用以下代码来检查表单字段检查模式和验证,它也会动态创建字段。

import React from 'react';
import { TouchableOpacity, View } from 'react-native';

const VALIDATE_USERFORM = {
  mobileNumber: {
    message: 'Enter your phone number',
    pattern: /^.{8}$/,
    error: "Wrong mobile number format",
  },
  // Other fields pattern and error message ...
}

class UserForm extends React.Component {
  constructor(props) {
    super(props);

    this.inputs = {};

    this.state = { ...this.generateDoc() };

    this.onSubmit = this.onSubmit.bind(this);
    this.onInputChange = this.onInputChange.bind(this);
  }

  onSubmit() {
    const doc = this.state;

    this.validateFields();

    this.props.save(doc, () => {
      console.lo('Successfully saved');
    });
  }

  focusField = name => {
    this.inputs[name].focus();
  };

  validateFields() {
    const fields = this.state;

    const names = Object.keys(fields);

    for (const name of names) {
      const validate = VALIDATE_USERFORM[name] || {};

      if (fields[name].length === 0) {
        // Empty
        return console.log(validate.message);
      }

      if (!fields[name].match(validate.pattern)) {
        // Pattern does not match
        return console.log(validate.error);
      }
    }
  }

  generateDoc() {
    const data = this.props.data || {};

    return {
      mobileNumber: data.mobileNumber || '',
      username: data.username || '',
      password: '',
    };
  }

  onInputChange(name, value) {
    this.setState({ [name]: value });
  }

  renderControl(args) {
    const {
      minLength,
      keyboardType,
      secureTextEntry,
      maxLength,
      onSubmitEditing,
      autoFocus,
      name,
      label,
      type,
    } = args;

    let control;

    const props = {
      autoFocus,
      secureTextEntry,
      onSubmitEditing,
      maxLength,
      minLength,
      keyboardType,
    };

    control = (
      <TextInput
        ref={e => (this.inputs[name] = e)}
        value={this.state[name]}
        onChangeText={e => this.onInputChange(name, e)}
        secureTextEntry={secureTextEntry}
        style={styles.input}
        returnKeyType="next"
        {...props}
      />
    );

    return this.renderField(label, control);
  }

  renderField(label, control) {
    return (
      <View style={styles.field}>
        <Text style={styles.label}>{label}*</Text>
        {control}
      </View>
    );
  }

  renderForm() {
    return (
      <View style={styles.wrapper}>
        <KeyboardAwareScrollView>
          {this.renderControl({
            name: 'mobileNumber',
            label: 'Mobile number',
            maxLength: 10,
            onSubmitEditing: () => this.focusField('username),
          })}
          {this.renderControl({
            name: 'username',
            label: 'Username',
            maxLength: 16,
            minLength: 6,
            onSubmitEditing: () => this.focusField('Password'),
          })}
          {this.renderControl({
            name: 'password',
            label: 'Password',
            maxLength: 16,
            minLength: 6,
            secureTextyEntry: true
          })}
        </KeyboardAwareScrollView>
      </View>
    );
  }

  renderButton(label, onPress) {
    return (
      <TouchableOpacity style={styles.button}} onPress={onPress}>
        <Text style={styles.buttonText}>{label.toUpperCase()}</Text>
      </TouchableOpacity>
    );
  }

  renderFooter() {
    return (
      <View style={styles.footer}>
        {this.renderButton('Save', this.onSubmit)}
      </View>
    );
  }

  render() {
    return (
      <View>
        {this.renderForm()}
        {this.renderFooter()}
      </View>
    );
  }
}

export default UserForm;
 类似资料:
  • 因此,我有一个包含许多的表单,它们都需要填写。我研究了文本框验证,但我只能找到验证单个文本框的说明。下面是单数文本框验证的代码。我只是想知道是否有可能同时打击所有的人,而不是每个人都这样。任何帮助都将不胜感激!

  • 我如何验证一个列表的值跨字段,其中至少一个单一的值必须设置(不是零) 我需要验证至少有一个字段被输入(例如总数不是零) 我遇到的问题是,当任何一个字段发生更改时,validator::total_cost不会重新评估所有正在验证的字段。 在“任意”输入中键入正确的值需要告诉“所有”其他输入,以便根据新的计算字段重新估价! 任何帮助都将不胜感激。 (我的电视机大得多) 我正在使用的标记 AnyVal

  • 问题内容: 我试图做一个多项式运算符(两个,多个多项式的和,余数,乘法和除法)。该代码必须使用Java并使用链接列表。 我想知道如何使用计算器或如何验证多项式是否有效。我想从字符串构造一个多项式,但是我不知道是否有另一个类可以简化事情。 这是一项家庭作业,因此我并不需要完整的代码,只是为我指明了正确的方向。 有两类,一类用于节点(命名为Monomio),一类用于列表(命名为Polinomio,是单

  • 问题内容: 我正在尝试使用SuperCSV将数据库中的大量行(约200万行)写入CSV文件。我需要在每个单元格编写时对其进行验证,并且内置的CellProcessor表现得非常好。我想捕获CellProcessors抛出的所有异常,以便可以返回到源数据并进行更改。 问题是,当一行中存在多个错误时(例如,第一个值超出范围,第二个值为null,但不应为空),只有第一个CellProcessor会执行,

  • D:\reactnative\awesomeproject>react-native run-android info运行jetifier将库迁移到AndroidX。您可以使用“--no-jetifier”标志禁用它。Jetifier找到863个文件要转发JEtify。使用4个工作者...信息正在启动JS服务器...信息正在启动仿真程序...错误:无法启动仿真程序。原因:未找到作为输出的仿真器。警

  • 问题内容: 我正在使用JPA 2.0 /hibernate验证来验证我的模型。我现在遇到一种情况,必须验证两个字段的组合: 该模型是无效的,如果都和都null和其他有效。 如何使用JPA 2.0 / Hibernate执行这种验证?使用简单的注释,两个吸气剂都必须为非null才能通过验证。 问题答案: 对于多属性验证,应使用类级别的约束。摘自 Bean Validation Sneak Peek第