【问题标题】:Javascript 'If' to see if a form field has a number in it?Javascript'If'查看表单字段中是否有数字?
【发布时间】:2014-05-18 08:14:13
【问题描述】:

如果表单字段中没有手动输入数字,我在 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">

而且我知道数据是通过 via

position : req.body.position,

因为console.log(req.body.position); 确实记录了号码

【问题讨论】:

  • 不清楚你的代码是如何/何时执行的,以及一切是如何相互关联的。如果没有清楚地了解代码的作用,就很难提供帮助。
  • 如果 position 是从 HTML 元素填充的,它将是一个 字符串值。 Stack Overflow 上有很多关于检查值是否为数字的帖子。
  • 我猜position 是值,而且它始终是一个字符串,所以检查 typeof 失败得很惨。你想要isNaN
  • 位置在 Mongoose 模型中被定义为一个数字,但这没有区别吗? position: Number,
  • @FelixKling 为代码清晰添加了上下文.. 这更有帮助吗?

标签: javascript node.js angularjs mongodb mongoose


【解决方案1】:

试试这个:

// 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() 将根据浏览器的年龄返回 nullNaN。如果传递了错误值(NaN,未定义)或 null,则“或”函数将返回辅助项(在本例中为 -1)。您可以更改以将 -1 值更改为您想要的任何值。我只是喜欢数字,因为它们比字符串占用更少的内存字节并且处理速度更快。

【讨论】:

  • 这会返回一个 ReferenceError: position is not defined in the console, and a 500 internal server error on the browser network.. 谢谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-06-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-03-28
  • 2014-11-06
相关资源
最近更新 更多