【问题标题】:Input field validation using regex in ReactJS在 ReactJS 中使用正则表达式验证输入字段
【发布时间】:2022-07-18 23:35:09
【问题描述】:

我在 ReactJS 中创建了一个基本的验证表单,使用正常条件来验证输入字段。

现在我想使用正则表达式来验证输入字段,而不是使用下面使用的基本条件。

我现在的代码是这样的:

import React, { useState } from 'react';
import { Button, Form } from 'semantic-ui-react'
import axios from 'axios';
import { useNavigate, NavLink } from 'react-router-dom';
import Swal from 'sweetalert2';

function Create() {
    let navigate = useNavigate();

    const [password, setPassword] = useState('');
    const [email, setEmail] = useState('');
    const [companyNumber, setCompanyNumber] = useState('');;

    const postData = () => {

        const url = `https://62c45bb0abea8c085a73b996.mockapi.io/Reactcrud`

            if(password.length <= 4){
                return Swal.fire({
                    icon: 'error',
                    title: 'Error',
                    text: 'password must contain atleast 4 digits',
                    showConfirmButton: true
                  })
            }else if(companyNumber.length !== 10){
                return Swal.fire({
                    icon: 'error',
                    title: 'Error',
                    text: 'mobile number should be a 10 digit number',
                    showConfirmButton: true
                  })
            }else{
                axios.post(url, {
                    password,
                    email,
                    companyNumber,
                })
    
            .then(() => {
                navigate('/company/list');
            })
            }
            
    }

    const goBack = () =>{
        navigate("/company/list")
    } 

    return (
        <div className='container-fluid'>
        <div className='row'>
        <div className='col-lg-4'></div>
        <div className='text-black align-content-center col-lg-5 '>
            <Form className="create-form">
                <Form.Field>
                    <label>Password</label>
                    <input  placeholder='enter password' onChange={(e) => setPassword(e.target.value)}/>
                </Form.Field>
                <Form.Field>
                    <label>Email Address</label>
                    <input  placeholder='Email' onChange={(e) => setEmail(e.target.value)}/>
                </Form.Field>
                <Form.Field>
                    <label>Company Mobile Number</label>
                    <input  placeholder='Company Number' onChange={(e) => setCompanyNumber(e.target.value)}/>
                </Form.Field>
                <Button color="blue" onClick={postData} type='submit'>Submit</Button>
                 <Button color="red" onClick={goBack}>
                    Cancel
                 </Button>
            </Form>
        </div>
        </div>
        </div>
    )
}

export default Create;

在上面的手机号码验证和密码验证代码中,我添加了一个输入条件为 10 位数字。

现在我希望它使用这个正则表达式来验证手机号码:

const regex1 = /^(\+91[-\s]?)?[0]?(91)?[789]\d{9}$/;

这用于密码验证:

const regex2 = /^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[!@#$%^&*_=+-]).{4,12}$/;

如您所见,我使用了一个基本条件来验证输入字段,现在我想添加一个正则表达式来根据正则表达式验证密码字段和手机号码字段。

请帮助我根据我想要使用正则表达式的要求完成验证工作。

【问题讨论】:

    标签: javascript reactjs regex validation


    【解决方案1】:

    我已经改变了 else if 语句中的条件,如下所示,它可以解决问题。

    import React, { useState } from 'react';
    import { Button, Form } from 'semantic-ui-react'
    import axios from 'axios';
    import { useNavigate, NavLink } from 'react-router-dom';
    import Swal from 'sweetalert2';
    
    function Create() {
        let navigate = useNavigate();
    
        const [password, setPassword] = useState('');
        const [email, setEmail] = useState('');
        const [companyNumber, setCompanyNumber] = useState('');;
    
        const postData = () => {
    
            const url = `https://62c45bb0abea8c085a73b996.mockapi.io/Reactcrud`
    
            const regex = /^(\+91[-\s]?)?[0]?(91)?[789]\d{9}$/;
    
                if(password.length <= 4){
                    return Swal.fire({
                        icon: 'error',
                        title: 'Error',
                        text: 'password must contain atleast 4 digits',
                        showConfirmButton: true
                      })
                }else if(!regex.test(companyNumber)){
                    return Swal.fire({
                        icon: 'error',
                        title: 'Error',
                        text: 'mobile number should be a 10 digit number',
                        showConfirmButton: true
                      })
                }else{
                    axios.post(url, {
                        password,
                        email,
                        companyNumber,
                    })
        
                .then(() => {
                    navigate('/company/list');
                })
                }
                
        }
    
        const goBack = () =>{
            navigate("/company/list")
        } 
    
        return (
            <div className='container-fluid'>
            <div className='row'>
            <div className='col-lg-4'></div>
            <div className='text-black align-content-center col-lg-5 '>
                <Form className="create-form">
                    <Form.Field>
                        <label>Password</label>
                        <input  placeholder='enter password' onChange={(e) => setPassword(e.target.value)}/>
                    </Form.Field>
                    <Form.Field>
                        <label>Email Address</label>
                        <input  placeholder='Email' onChange={(e) => setEmail(e.target.value)}/>
                    </Form.Field>
                    <Form.Field>
                        <label>Company Mobile Number</label>
                        <input  placeholder='Company Number' onChange={(e) => setCompanyNumber(e.target.value)}/>
                    </Form.Field>
                    <Button color="blue" onClick={postData} type='submit'>Submit</Button>
                     <Button color="red" onClick={goBack}>
                        Cancel
                     </Button>
                </Form>
            </div>
            </div>
            </div>
        )
    }
    
    export default Create;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-06-15
      • 2021-11-28
      相关资源
      最近更新 更多