vue/react表单检验为空不通过

  • 时间:
  • 来源:互联网
  • 文章标签:

1、Vue版

说明:
(1)如果检验未通过,input框的border-color会变成红色;
(2)ref的值和v-model绑定值的key必须一样才能生效;

<template>
	<input ref='title' ref='title' v-model='formData.title'/>
	<input ref='name' ref='name' v-model='formData.name'/>
	<button @click="submit">提交</button>
</template>
<script>
data(){
	return{
		formData:{
			title:'',
			name:'',
			}
	}
},
methods:{
	inspection(value){
		Object.keys(value).some(
			(item) => {
				if (this.$refs[item].value === '') {
	    			this.$refs[item].style.borderColor = '#ff0000'
				} else {
	    			this.$refs[item].style.borderColor = '#999999'
				}
			}
		);
		const flag = Object.keys(value).findIndex(
			(item) => {
				return this.$refs[item].value === ''
				})
		if (flag !== -1) {
			alert('必填项不可为空!')
			return false
		} else {
			return true
		}
	},
	 submit(){
	 	const { title, name } = this.formData
	 	const mustData = { title, name }
	 	const flag = this.inspection()
	 	if(flag){
	 		this.ajax(this.formData)  //ajax函数自行封装
		}
	 }
 }
 </script>

2、React版

说明:
(1)如果检验未通过,input框的border-color会变成红色;
(2)ref的值和mustData的key必须一样才能生效;

import React, { Component, Fragment } from 'react'
interface Props {}
interface State {}
class PreviewGame extends Component<Props, State> {
	refs: any = React.createRef()
	inspection = (value) => {
	   Object.keys(value).some(
	     	(item) => {
	           if (this.refs[item].value === '') {
	               this.refs[item].style.borderColor = '#ff0000'
	           } else {
	               this.refs[item].style.borderColor = '#999999'
	           }
	       }
	   );
	   const flag = Object.keys(value).findIndex(
	      (item) => {
	           return this.refs[item].value === ''
	       })
	   if (flag !== -1) {
	       alert('不可为空')
	       return false
	   } else {
	       return true
	   }
	}
	submit = () => {
		const mustData = {
			title:this.refs.title.value,
			name:this.refs.name.value
		}
		const flag = this.inspection(mustData)
		if(flag){
			this.ajax()     // //ajax函数自行封装
		}
	}
}
render(){
	return(
		<Fragment>
			<input ref='title' ref='title'/>
			<input ref='name' ref='name' />
			<button onClick={this.submit}>提交</button>
		</Fragment>
	)
}

本文链接http://www.taodudu.cc/news/show-1944507.html