1、下载
npm install validator
import Taro from '@tarojs/taro'
import { View, Text, Form } from '@tarojs/components'
import classnames from 'classnames'
import validator from 'validator'
export default class ModifyPasswordPage extends Taro.Component {
constructor(props) {
super(props)
this.state = {
oldPassword: '',
newPassword: '',
confirmPassword: '',
errors: {
oldPassword: '',
newPassword: '',
confirmPassword: ''
}
}
}
validatePassword = (password, errors, field) => {
const isValid = validator.isLength(password, { min: 6, max: 20 })
if (!isValid) {
errors[field] = '密码长度必须在6到20个字符之间'
} else {
errors[field] = ''
}
this.setState({ errors })
return isValid
}
handleSubmit = e => {
e.preventDefault()
const { oldPassword, newPassword, confirmPassword } = this.state
const errors = {}
const isOldPasswordValid = this.validatePassword(oldPassword, errors, 'oldPassword')
const isNewPasswordValid = this.validatePassword(newPassword, errors, 'newPassword')
const isConfirmPasswordValid = newPassword === confirmPassword
if (!isConfirmPasswordValid) {
errors.confirmPassword = '确认密码与新密码不一致'
this.setState({ errors })
}
if (isOldPasswordValid && isNewPasswordValid && isConfirmPasswordValid) {
// 执行密码修改逻辑
Taro.showToast({ title: '密码修改成功', icon: 'success' })
} else {
Taro.showToast({ title: '密码修改失败', icon: 'none' })
}
}
render() {
const { oldPassword, newPassword, confirmPassword, errors } = this.state
return (
<Form onSubmit={this.handleSubmit}>
<View className='form-item'>
<Text className='label'>旧密码:</Text>
<Input
className={classnames({ 'input-error': errors.oldPassword })}
value={oldPassword}
onInput={e => this.setState({ oldPassword: e.target.value })}
placeholder='请输入旧密码'
type='password'
/>
{errors.oldPassword && <Text className='error-msg'>{errors.oldPassword}</Text>}
</View>
<View className='form-item'>
<Text className='label'>新密码:</Text>
<Input
className={classnames({ 'input-error': errors.newPassword })}
value={newPassword}
onInput={e => this.setState({ newPassword: e.target.value })}
placeholder='请输入新密码'
type='password'
/>
{errors.newPassword && <Text className='error-msg'>{errors.newPassword}</Text>}
</View>
<View className='form-item'>
<Text className='label'>确认密码:</Text>
<Input
className={classnames({ 'input-error': errors.confirmPassword })}
value={confirmPassword}
onInput={e => this.setState({ confirmPassword: e.target.value })}
placeholder='请再次输入新密码'
type='password'
/>
{errors.confirmPassword && <Text className='error-msg'>{errors.confirmPassword}</Text>}