Javascript'如果'以查看表单字段中是否包含数字?

时间:2014-04-06 03:02:33

标签: javascript node.js angularjs mongodb mongoose

如果在表单字段中没有手动输入数字,我在Mongoose Schema中有一些javascript来自动递增值。

// before validation starts, the number of Items is counted..afterwards, the position is set

    ItemSchema.pre("validate", function(next) {

        var doc = this;

        // if 'position' is not filled in, fill it in..not using !position because 0 might be a valid value
        if(typeof position !== "number") {
            // count the number of Items *
            // use mongoose.model to fetch the model because the model is not compiled yet
            mongoose.model("Item").count(function(err, num) {
                // if there was an error, pass it to next()
                if(err)
                    return next(err);

                // set the position, then call next();
                doc.position = num;
                return next();
            });
        } else if(this.isModified("position") || this.isNew()) {
            // code to check if there is an existing document with the same position 
            // code to check move down other document positions, if existing

自动递增工作正常,但无论字段中是否有数字,它都会执行此操作。什么是更好的“if声明”?

我在前端有这个表单字段:

<input type="number" class="form-control input-lg text-center" placeholder="Position" ng-model="formData.position">

我知道数据正在通过

传递
position : req.body.position,

因为console.log(req.body.position);会记录数字

1 个答案:

答案 0 :(得分:0)

试试这个:

// if 'position' is not filled in, fill it in
// not using !position because 0 might be a valid value
if( (parseFloat(position) || -1) == -1) {
// code for auto-incrementing

parseFloat()将返回 null NaN ,具体取决于浏览器的使用期限。 &#39;或&#39;函数将在传递错误值(NaN,未定义)或null的情况下返回辅助(在本例中为-1)。您可以更改为将-1值更改为您想要的任何值。我只是喜欢数字,因为它们占用了少量字节的内存然后字符串,并且处理起来更快。