在meteorjs中进行表单验证

时间:2014-05-14 20:58:49

标签: meteor

我正在对meteorjs中的输入进行简单的验证,在第一次巡视后它会起作用,并且每次下次它都不起作用(直到我重新加载页面) - 这意味着不会显示错误消息。

//main.js//
Template.addMealForm.events({
    'click #submitNewMeal': function (ev) {
        ev.preventDefault();
        var query = {
            name: $("#name").val().trim(),
            price: $("#price").val(),
            calories: $("#calories").val(),
            category: $("#category").val()
        };
        areInputsValid(query);
    }
});

var areInputsValid = function (query) {
    if ((query.name.length === 0) || (query.price.length === 0) || (query.calories.length === 0)) {
        $("#warningLabel").addClass("di")
        $(".warningLabel").text("All fields are required");

    }
    else if ((isNaN(query.price) === true) || (isNaN(query.calories) === true)) {
        $("#warningLabel").addClass("di")
        $(".warningLabel").text("To Price and Calories fields please enter a number");
    }
    else {
        console.log('it works');
        $('.dn').hide();
    }
};

// // main.html中

<template name="addMealForm">                
        <form role="form">
            <div class="form-group">
                <label for="name">Name</label>
                <input type="text" class="form-control input_form" id="name" placeholder="Name of the meal">
            </div>
            <div class="form-group">
                <label for="price">Price</label>
                <input class="form-control input_form" id="price" placeholder="Price">
            </div>
            <div class="form-group">
                <label for="calories">Calories</label>
                <input class="form-control input_form" id="calories" placeholder="Calories">
            </div>                
            <div id="warningLabel" class="form-group has-error dn">
                <label class="control-label warningLabel"></label>
            </div>
            <button id="submitNewMeal" type="submit" class="btn btn-rimary">Add</button>
        </form>
</template>

2 个答案:

答案 0 :(得分:4)

问题是您在成功案例中呼叫$('.dn').hide()。由于#warningLabel的类别为dn,因此后续错误不会再次显示。

一种解决方案是将$('.dn').show()添加到areInputsValid的顶部。

答案 1 :(得分:0)

你已经将Tracker作为Meteor的一部分,所以我将一个小教程和JSfiddle放在一起,讨论如何使用它来实现典型的表单验证方案。

http://bit.ly/meteor-form-validation-video

http://bit.ly/meteor-form-validation-fiddle