mongoose+express+jQuery Validate实现用户表单异步验证

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

mongoose+express+jQuery Validate实现用户表单异步验证_第1张图片
图片.png

mongoose+express+jQuery Validate实现用户表单异步验证_第2张图片
图片.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页面

用户名:
密 码:
确认密码:

四、用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

你可能感兴趣的:(mongoose+express+jQuery Validate实现用户表单异步验证)