简体   繁体   中英

Number validation in html form on input of type number

I am thinking all possibilities that a user can enters into a <input> of type number and using jquery to validate the input.

In the input field, I put in just a simple dot '.'

if($("#timetaken").val() == "")

and this if statement executed with the response saying it is empty. There is a '.' dot in it and logically speaking it should skip this and execute the else that tells us it is not empty.

I also tested with the input "1." that is incomplete with

console.log($("#timetaken").val().toString().indexOf("."));

and it returns -1, which means the '.' is not there and ignored.

The question is there a way to validate these two inputs in an <input> tag of type number?

Thank you.

If you try to test a number input with some non-number characters (like a single dot).. Yes, sure the empty passes.

I would suggest you to use a text input with a regular expression to test the value as you wish. This input type has no strange behavior or restriction and a "regex" can exactly test the value for whatever requirement you have.

That would be (from what I can read from your question) something like:

 $("#go").on("click",function(){ var value = $("#test").val(); var regex = /((\\d){1,9}\\.?\\d*)|(\\d*\\.?(\\d){1,9})/; // {1,9} means at least 1 and up to 9 digits. if(regex.test(value)){ console.log("Value is ok"); }else{ console.log("Value fails."); } }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input type="text" id="test"> <button id="go">Test</button> 

So floating numbers or natural numbers are ok. Nothing else.

Regex tester: regex101 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM