Getting Started with React - Encapsulation of complex form methods and implementation of form validation functions (encapsulation optimization of form validation methods)

foreword

In front-end development, form validation is a very common function. This article will talk about the function of getting started with react to realize complex forms, and the realization of form validation function.

Implementation of complex form pages

Implement a form page, including input boxes, radio buttons and drop-down boxes, click submit to get the input data
1. First define our unrestricted component Hello, and define the variables we need to use in state:

class Hello extends React.Component {
    
    
            state = {
    
    
                name: '',
                sex: '2',
                select: 'A',
                select2: '',
                select3: '',
                text: 'hello world'
            }
        }

2. Then write our render() method in the component:
first structure the state defined above, define the arr1 array to store the data required by the drop-down box, and arr2 is an array object, which is also the most commonly used in our actual opening. The format is used to render another drop-down box
and then start writing the content of the page in return

render() {
    
    
    let {
    
     name, sex, select, select2, select3, text } = this.state
    let arr1 = ['D', 'E', 'F', 'G', 'H']
    let arr2 = [{
    
    id: 1, color: 'red'}, {
    
    id: 2, color: 'green'}, {
    
    id: 3, color: 'blue'}]
    return <div>
        <form>
            <label>姓名:<input type="text" name="name" defaultValue={
    
    name} onChange={
    
    this.handleChange} /></label><br/>
            <label>性别:
                <input type="radio" name='sex' value="1"
                defaultChecked={
    
    sex === '1' ? true : false}
                onChange={
    
    this.handleChange}/><input type="radio" name='sex' value="2"
                defaultChecked={
    
    sex === '2' ? true : false}
                onChange={
    
    this.handleChange}/></label><br/>
            <label>写死的选项:
                <select name="select" defaultValue={
    
    select} onChange={
    
    this.handleChange}>
                    <option value="A">A</option>
                    <option value="B">B</option>
                    <option value="C">C</option>
                    <option value="D">D</option>
                </select>
            </label><br/>
            <label>循环遍历出来的选项:
                <select name="select2" defaultValue={
    
    select2} onChange={
    
    this.handleChange}>
                    {
    
    
                        arr1.map((item, index) =>
                            <option key={
    
    index} value={
    
    item}>{
    
    item}</option>
                        )
                    }
                </select>
            </label><br/>
            <label>数组中是对象的数据循环遍历处理:
                <select name="select3" defaultValue={
    
    select3} onChange={
    
    this.handleChange}>
                    {
    
    
                        arr2.map(item =>
                            <option key={
    
    item.id} value={
    
    item.id}>{
    
    item.color}</option>
                        )
                    }
                </select>
            </label><br/>
            <label>备注信息:
                <textarea name="text" defaultValue={
    
    text} onChange={
    
    this.handleChange}></textarea>
            </label>
        </form>
        <button onClick={
    
    this.handleSubmit}>点击提交</button>
    </div>
}

In the above select, we use the loop to show the content in arr1. The second select is the processing method of looping through the data of the objects in the array. Pay attention to their different writing methods.

3. Add an onChange event to each input box and an onClick event to the button to submit the form
. Let’s write these two functions:
handleChange is the time when the value of the input box is changed. We bind the name value to each element, Then encapsulate it, note that this.setState is in the form of [name], an array, e.target.value gets the input value and assigns
handleSubmit to submit the value of the form, and then print it out

handleChange = (e) => {
    
    
    let name = e.target.name
    this.setState({
    
    [name]: e.target.value})
}
handleSubmit = () => {
    
    
    console.log(this.state)
}

Show results:

insert image description here

form validation method

Let's talk about how to add form validation to the form. I don't need the above form here. Write a new form that includes a nickname, password, and mobile phone number. Let's see how to implement form validation:

Then add a span tag after the input box to display the error message, and bind the corresponding error message such as {nameError}

return <div>
    <form>
        <label>姓名:<input type="text" name="name"
            defaultValue={
    
    name} onChange={
    
    this.nameChange} />
            <span className='danger'>{
    
    nameError}</span>
        </label><br/>
        <label>密码:<input type="password" name="password"
            defaultValue={
    
    password} onChange={
    
    this.passChange} />
            <span className='danger'>{
    
    passwordError}</span>
        </label><br/>
        <label>性别:
        <input type="radio" name="sex" value="1"
            checked={
    
    sex === '1' ? true : false} onChange={
    
    this.handleClick} />
        <input type="radio" name="sex" value="2"
            checked={
    
    sex === '2' ? true : false} onChange={
    
    this.handleClick} />
        </label><br/>
        <label>手机号:<input type="text" name="phone"
            defaultValue={
    
    phone} onChange={
    
    this.phoneChange} />
            <span className='danger'>{
    
    phoneError}</span>
        </label><br/>
        <label>选择城市:
            <select name="select" defaultValue={
    
    select} onChange={
    
    this.handleClick}>
                {
    
    
                    arr.map(item => {
    
    
                        return <option key={
    
    item.id} value={
    
    item.id}>{
    
    item.city}</option>
                    })
                }
            </select>
        </label><br/>
    </form>
    <button onClick={
    
    this.handleSubmit}>点击提交</button>
</div>

Then define the function of form validation:
judge the value passed by the component, and give the corresponding error display

// 姓名校验处理
nameChange = (e) => {
    
    
     let rule = /^[a-zA-Z0-9]{4,10}$/
     let value = e.target.value
     let error = ''
     if(!value) {
    
    
         error = '请输入昵称'
     } else if (!rule.test(value)) {
    
    
         error = '请输入4-10位昵称'
     } else {
    
    
         error = ''
     }
     this.setState({
    
    
         name: value,
         nameError: error
     })
 }
 
 passChange = (e) => {
    
    
     let rule = /^\S*(?=\S{6,12})(?=\S*\d)(?=\S*[A-Z])(?=\S*[a-z])(?=\S*[!@#$%^&*? ])\S*$/
     let value = e.target.value
     let error = ''
     if(!value) {
    
    
         error = '请输入密码'
     } else if (!rule.test(value)) {
    
    
         error = '请输入6-12需要包含大小写字母和数字以及特殊符号'
     } else {
    
    
         error = ''
     }
     this.setState({
    
    
         password: value,
         passwordError: error
     })
 }

 phoneChange = (e) => {
    
    
     let rule = /^(?:(?:\+|00)86)?1[3-9]\d{9}$/
     let value = e.target.value
     let error = ''
     if(!value) {
    
    
         error = '请输入手机号'
     } else if (!rule.test(value)) {
    
    
         error = '请输入格式正确的手机号'
     } else {
    
    
         error = ''
     }
     this.setState({
    
    
         phone: value,
         phoneError: error
     })
 }

Look at the effect:
insert image description here
In this way, we have realized the form verification, but if the form content is more, then the verification code will be written a lot, how to optimize this part? continue down

Optimization of form validation methods

For the above form validation method, it is obvious that there are many repetitions, so it can be encapsulated
Write the content of the rule in the form of passing parameters,
and use new RegExp in the function to describe the regularity, e.target.getAttribute('rule') Get the value of rule and
use name+'Error' to concatenate the name for assignment

// 校验方法封装
handleChange(e, info1, info2){
    
    
    // console.log(e.target);
    let {
    
     name, value } = e.target
    let rule = new RegExp(e.target.getAttribute('rule'))
    let error = ''
    if(!value) {
    
    
        error = info1
    } else if (!rule.test(value)) {
    
    
        error = info2
    } else {
    
    
        error = ''
    }
    this.setState({
    
    
        [name]: value,
        [name + 'Error']: error
    })
}
<label>姓名:<input type="text" name="name"
    rule="^[a-zA-Z0-9]{4,10}"
    defaultValue={
    
    name} onChange={
    
    (e) => this.handleChange(e, '请输入昵称','请输入4-10位昵称')} />
    <span className='danger'>{
    
    nameError}</span>
</label><br/>
<label>密码:<input type="password" name="password"
    rule="^\S*(?=\S{6,12})(?=\S*\d)(?=\S*[A-Z])(?=\S*[a-z])(?=\S*[!@#$%^&*? ])\S*$"
    defaultValue={
    
    password} onChange={
    
    (e) => this.handleChange(e, '请输入密码','请输入6-12需要包含大小写字母和数字以及特殊符号')} />
    <span className='danger'>{
    
    passwordError}</span>
</label><br/>
<label>性别:
<input type="radio" name="sex" value="1"
    checked={
    
    sex === '1' ? true : false} onChange={
    
    this.handleClick} />
<input type="radio" name="sex" value="2"
    checked={
    
    sex === '2' ? true : false} onChange={
    
    this.handleClick} />
</label><br/>
<label>手机号:<input type="text" name="phone"
    rule="^(?:(?:\+|00)86)?1[3-9]\d{9}$"
    defaultValue={
    
    phone} onChange={
    
    (e) => this.handleChange(e, '请输入手机号','请输入格式正确的手机号')} />
    <span className='danger'>{
    
    phoneError}</span>
</label><br/>

Is it a lot less code to write this way, and the effect is exactly the same

If it is helpful to you, please like and support it. Follow me and I will bring more high-quality content in the future~
insert image description here

Guess you like

Origin blog.csdn.net/weixin_45745641/article/details/123430659