mongoose+express+jQuery Validate

2017-03-24  本文已影响0人  _李雷

mongoose入门学习:https://github.com/i5ting/nodejs-fullstack/blob/master/mongoose.md
jQuery Validate:http://www.runoob.com/jquery/jquery-plugin-validate.html
完成功能如图所示:填入已经存在的用户名会提示“请修正此字段”

图片.png
图片.png

一、建立数据库模型

var config = require('config-lite');
var mongoose = require("mongoose");
mongoose.Promise = global.Promise;
mongoose.connect(config.mongodb);
var Schema = mongoose.Schema;
var UserSchema = new Schema({
    username:String,
    password:String
});
UserSchema.index({username:1});
module.exports = mongoose.model('User',UserSchema);

二、对数据库进行操作

var UserModel = require('../lib/mongo');

 module.exports ={
     //创建一个用户
     create:function create(user){
        return UserModel.create(user);
     },

    //通过用户名获取用户信息
    getUserByName:function getUserByName(username){
        return UserModel.findOne({username:username}).exec();

    }
}

三、ejs页面

<form method="post"  id="foo">
    用户名:<input type="text" name="name" id="username" required="true"><br/>
    密  码:<input type="password" name="password" id="password" required="true"><br/>
    确认密码:<input type="password" name="repassword" required="true"><br/>
    <input type="submit" value="注册">
</form>

<script src="http://static.runoob.com/assets/jquery-validation-1.14.0/lib/jquery.js"></script>
<script src="http://static.runoob.com/assets/jquery-validation-1.14.0/dist/jquery.validate.min.js"></script>
<script src="http://static.runoob.com/assets/jquery-validation-1.14.0/dist/jquery.validate.min.js"></script>
<script src="http://static.runoob.com/assets/jquery-validation-1.14.0/dist/localization/messages_zh.js"></script>
<script src="user.js"></script>

四、用jQuery Validate验证

var validator = $("#foo").validate({
    rules: {
        name: {
            required: true,  // 必须输入
            rangelength: [1,10],// 输入字符串长度在2-10之间
            remote:{
                url:"/signup/signupcheck", //后台处理数据地址
                type:"post",
                dataType:"json",
                data:{
                    username:function(){
                        return $("#username").val();
                    }
                }
            }
        },
        password: {
            required: true,
            minlength: 6// 输入字符串最短长度为6
        },
        repassword: {
            required: true,
            minlength: 6,
            equalTo: "#password" // 输入的值必须和#password中的值相等,用于判断两次输入的密码是否相等
        }
    },

});

五、注册

var sha1=require('sha1');
var express = require('express');
var bodyParser = require('body-parser');
var router =express.Router();
//var UserModel = require('../lib/mongo');
var UserModel = require('../models/users');

router.get('/',function(req,res,next){
    res.render('signup.ejs');
});

router.post('/',function(req,res,next){
    var username = req.body.name; //从表单获取name
    var password = req.body.password;
    var repassword = req.body.repassword;

    //待写入数据库的信息
    var user={
        username:username,
        password:password,
    }

    UserModel.create(user)
        .then(function(result){
           req.session.user=user;
           //req.flash('success','注册成功');
            res.redirect('/login');
         })
});


router.post('/signupcheck',function(req,res,next){
    var name = req.body.name; 
    user = req.session.user;

    UserModel.getUserByName(name)     // UserModel是用户操作数据库的模型,getUserByName 方法是查找name用户
        .then(function (user) {
            console.log(user);
            if (user) {
                res.json(false);
                //console.log("用户已经存在");
            } else {
                res.json(true);
            }
        })
        .catch(next);

});

module.exports = router;

使用body-parser中间件一定要这样写:

app.use(bodyParser.urlencoded({
extended: true
}));

完整代码地址:https://github.com/leilei573249453/signup

上一篇下一篇

猜你喜欢

热点阅读