how to retrieve any inserted string in input type

2019-08-07 06:24发布

Is there any way of getting the inserted string(of any sort) from:

<input type="number" id='zipCode' name='zipcode' />

I'm trying to get value in console as:

console.log(document.getElementbyId('zipCode').value);

is giving just a blank output when any invalid string(string containing any alphabet or other special characters) is inserted which is also the same when actually left the field blank. But I want to retrieve the actual inserted value so that I can differentiate and validate the blank field with error message "Zipcode Field Empty!" and on invalid character string with error message "Invalid Zipcode!". Is there any way to retrieve any sort of inserted string from input type='number' field?

2条回答
我欲成王,谁敢阻挡
2楼-- · 2019-08-07 07:05

From what I remember reading (example here - HTML5 input type=number value is empty in Webkit if has spaces or non-numeric characters?) there is no way of doing this with the input type set to number.

查看更多
我命由我不由天
3楼-- · 2019-08-07 07:09

HTML input fields used for Zip Codes should be type=text and use the pattern attribute to provide hints to the browser

A numeric ZIP code is -- in a small way -- misleading.

Numbers should mean something numeric. ZIP codes don't add or subtract or participate in any numeric operations. 12309 - 12345 does not compute the distance from downtown Schenectady to my neighborhood.

ZIP codes aren't numbers -- they just happen to be coded with a restricted alphabet -- I suggest avoiding a numeric field. Same goes for credit card or social number

You can do <input type="text" pattern="\d*">. This will cause the numeric keyboard to appear on iOS (and Android?). Maybe it was pattern="[0-9]*"

"The semantically correct markup for a text field that can still contain whitespace and other special characters is <input type="text" inputmode="numeric"/> however as far as I am aware while inputmode is recommended by WhatWG it is not yet supported by any browsers. Its intent is to present the user with a numeric keypad on a device that has it but still behave as a text input." - davidelrizzo

查看更多
登录 后发表回答