2017-02-08 34 views
0

我从头开始创建自定义js验证器,而不使用任何库。检查用户插入值是否高于0用香草js

我想通过检查来验证数字input如果在input标签用户插入的内容比0是巨大的:

<label>Price 
    <input type="text" id="price" name="price"> 
</label> 

尝试:

function price() 
{ 
    if (#price.value>0) 
     console.log('0.'); 
    else 
     console.log('Incorrect'); 
} 
+3

你一些事情需要使用vanilla'document.getElementById('price')'来访问你的输入元素。 – lintmouse

+0

那么,你的问题是什么? – Turnip

+0

检查用户输入的值是否高于0用纯香草js –

回答

-1
function price() 
    { 
    var price = document.getElementById("#price"); // get the element 
    if (isNaN(price.value) || price.value <= 0) // if the value is not a number or is less than 0 
     console.log('Incorect'); 
    else // otherwise 
     console.log('Correct'); 
    } 
1

这会不会工作:

if(price.value.match(/^[0-9]+$/) && +(price.value) > 0){

即时通讯不太清楚哈希符号是用于什么,所以我在我的例子中删除它。除非你正在努力寻找的ID中,你将不得不寻找元素,像这样:

var price = document.querySelector("#price");

+0

这不起作用。输出错误'不能读取null的属性' –

-1

如何像

var price = document.getElementById("price").value; 
    if (parseInt(price) > 0 && !isNaN(price))) 
     { 
     // then do something 
     } 
    else 
     { 
     // else do something 
     } 
+0

@ down voter如果你投下任何问题解释并提出一些有关这个问题的建设性意见。 – MMK