实现一个注册功能,需要有用户名,密码,年龄,电子邮件,电子邮件需要在JS添加正则表达式验证,数据库表名:你的名称首字母大写_表名,列名:你的名称首字母大写_列名。(数据库建库语句,JQ,html,views关键代码贴上,
时间: 2024-03-20 18:45:04 浏览: 63
好的,以下是我提供的代码:
1. 数据库建库语句:
```
CREATE DATABASE YourName;
USE YourName;
CREATE TABLE YourName_Register (
ID INT(11) NOT NULL AUTO_INCREMENT,
Username VARCHAR(50) NOT NULL,
Password VARCHAR(50) NOT NULL,
Age INT(3) NOT NULL,
Email VARCHAR(50) NOT NULL,
PRIMARY KEY (ID)
);
```
2. HTML代码:
```
<form id="register-form">
<div class="form-group">
<label for="username">用户名:</label>
<input type="text" class="form-control" id="username" name="username" required>
</div>
<div class="form-group">
<label for="password">密码:</label>
<input type="password" class="form-control" id="password" name="password" required>
</div>
<div class="form-group">
<label for="age">年龄:</label>
<input type="number" class="form-control" id="age" name="age" required>
</div>
<div class="form-group">
<label for="email">电子邮件:</label>
<input type="email" class="form-control" id="email" name="email" required>
</div>
<button type="submit" class="btn btn-primary">注册</button>
</form>
```
3. JS代码:
```
$(document).ready(function() {
// 添加电子邮件的正则表达式验证
$.validator.addMethod("emailRegex", function(value, element) {
return this.optional(element) || /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/.test(value);
}, "请输入有效的电子邮件地址");
// 注册表单验证
$("#register-form").validate({
rules: {
username: {
required: true,
minlength: 3
},
password: {
required: true,
minlength: 6
},
age: {
required: true,
range: [18, 120]
},
email: {
required: true,
emailRegex: true
}
},
messages: {
username: {
required: "请输入用户名",
minlength: "用户名长度不能少于3个字符"
},
password: {
required: "请输入密码",
minlength: "密码长度不能少于6个字符"
},
age: {
required: "请输入年龄",
range: "请输入18到120之间的数字"
},
email: {
required: "请输入电子邮件地址"
}
},
submitHandler: function(form) {
// 表单验证通过后提交表单
$.ajax({
url: "register.php",
type: "POST",
data: $(form).serialize(),
success: function(response) {
if (response == "success") {
alert("注册成功");
window.location.href = "index.html";
} else {
alert("注册失败,请重试");
}
}
});
}
});
});
```
4. views代码:
```
def register(request):
if request.method == 'POST':
username = request.POST.get('username')
password = request.POST.get('password')
age = request.POST.get('age')
email = request.POST.get('email')
try:
# 数据库操作
conn = pymysql.connect(host='localhost', user='root', password='123456', database='YourName')
cursor = conn.cursor()
sql = "INSERT INTO YourName_Register (Username, Password, Age, Email) VALUES (%s, %s, %s, %s)"
cursor.execute(sql, (username, password, age, email))
conn.commit()
cursor.close()
conn.close()
return HttpResponse('success')
except:
return HttpResponse('error')
else:
return render(request, 'register.html')
```
注意:代码中的YourName需要替换为你的名称,例如我的名称是Tom,那么就需要将YourName替换为Tom。另外,数据库连接信息也需要根据自己的情况进行修改。
阅读全文