Using regex pattern in mobile with HTML5 input type number

Looking to create a regex pattern for an input field with type number that only allows numbers and dots. Here's what I've tried:

<input type="number" pattern="[0-9.]*">

<input type="tel">

Both options are allowing only numbers (0-9) but not displaying the dot (.). I actually need to use the dot in the input field.

Is it possible to achieve this through HTML5 or should I turn to JavaScript?

Note: This is working fine on Android devices, but the dot is not displaying on iPhones.

I want the mobile keypad to display like this...

Any advice on how to solve this issue?

Answer №1

When specifying "type=number" alone, the keypad on an iPhone will look like this:

If you add a pattern such as

<input type="number" pattern="\d*"/>
or
<input type="number" pattern="[0-9]*" />
, then the iPhone keypad will appear as follows:

However, note that it still cannot display a dot (.), as there is currently no pattern to handle this case.

You can consider using <input type="tel" /> which provides a keypad like this:

For more information on inputs for iOS, please check out the following links:

https://developer.mozilla.org/en-US/docs/Web/HTML/Input_element#The_step_attribute

https://css-tricks.com/instantly-preview-form-values-using-clever-active-fill-css-that-do-not-change-page-appearance/

I hope this information proves useful to you. :)

Customization Updates (source: )

You have the option to customize using JavaScript. For instance, you can create a currency input with decimal pattern where e.which reads the entered CharCode and pushes it into two arrays - one for digits before the decimal mark and another for values after the decimal mark.

Click here for a complete example

HTML:

<input type="tel" id="currency" />

JavaScript:

Variables and functions:

// declare variables
var i = 0,
    before = [],
    after = [],
    value = [],
    currency = '';

// reset all values
function clearValues() {
    i = 0;
    before = [];
    after = [];
    value = [];
    currency = '';
    $("#currency").val("");
    $(".amount").html("");
}

// adding a comma for thousand separator
function insertComma(num) {
    return num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}

Main code:

// listen for the keyup event
$("#currency").on("keyup", function (e, v) {

    // allow only numbers (0-9)
    if ((e.which >= 48) && (e.which <= 57)) {

        // convert CharCode into a number   
        currency = String.fromCharCode(e.which);

        // hide the entered value in the input field
        $(this).val("");

        // main array holding all numbers
        value.push(currency);

        // array for numbers before the decimal mark
        before.push(value[i]);

        // move numbers past the decimal mark
        if (i > 1) {
            after.push(value[i - 2]);
            before.splice(0, 1);
        }

        // final currency value
        var finalCurrency = after.join("") + "." + before.join("");

        // display the formatted value with commas
        $(this).val(insertComma(finalCurrency));

        // update the counter
        i++;

        // for demonstration purposes
        $(".amount").html(" " + $(this).val());

    } else {

        // reset all values
        clearValues();
    }
});

Reset Function:

// clear arrays when clear button is clicked
$(".ui-input-text .ui-input-clear").on("click", function () {
    clearValues();
});

Result:

Answer №2

Not all browsers support every input type and attribute. Generally, most modern browsers like IE10+ have basic support for email and number input types.

If a specific input type or attribute is not supported, the browser will default to a standard text input.

It's recommended to use a reliable regular expression pattern for validation.

For example:

<input type="tel" name="tel" pattern="^(?:\(\d{3}\)|\d{3})[- . ]?\d{3}[- . ]?\d{4}$" />
  • 1234567899
  • 123 456 7899
  • 123-456-7899
  • 123.456.7899

are all supported examples of 'tel' input type.

Browser support for 'tel' type

  • Android (yes)
  • iOS (yes)
  • IE (yes)
  • Mobile (yes)
  • Opera (yes)
  • Mobile (yes)
  • Opera (yes)
  • Classic (yes)
  • Opera Mini (no)
  • Firefox (yes)
  • Mobile (yes)
  • Chrome for Android (yes)

(Sources: caniuse.com, DeviceAtlas, mobilehtml5.org)

Browser support for pattern attribute

The pattern attribute is supported in Internet Explorer 10, Firefox, Opera, and Chrome. However, it is not supported in Internet Explorer 9 and earlier versions, or in Safari.

Answer №3

To display a numeric keypad with decimal input on iOS devices, utilize the type="number" and inputmode="decimal" attributes in your HTML input element.

Answer №4

I found myself in a similar situation where I needed to accommodate both comma and point for decimal marks and digit grouping [see here]

For example:

1.00 / 1,00
1,000,000.00 / 1.000.000,00

In addition, the requirement was to display the number keypad on mobile devices.

The initial solution involved using the 'number' type with the pattern attribute.

<input type="number" pattern="^(0*[,.]*[0-9][0-9]*([,.][0-9]+)*|[0-9]?[,.][0-9]*[1-9][0-9]*)$" required />

However, this setup resulted in validation errors for inputs that should have been allowed by the pattern, marking the field and form as invalid.

The solution was to switch the type to 'tel'.

<input type="tel" pattern="^(0*[,.]*[0-9][0-9]*([,.][0-9]+)*|[0-9]?[,.][0-9]*[1-9][0-9]*)$" required />

With this change, mobile users would now see a number keypad by default, and the pattern validation would accurately validate the input.

Answer №5

Regrettably, achieving the precise functionality you are seeking is not feasible at this time. However, there is a workaround solution that can provide similar results:

(Link no longer active)

This involves using a JavaScript code snippet that automatically fills in the decimal point as the user types, for example: 0.01 -> 0.12 -> 1.23 -> 12.34 . While it may not be an exact match, it can serve a similar purpose.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Adjust the height of an element when the maximum height is set to none

I am trying to add animation to the opening of a menu on my website. This is achieved by adjusting the max-height property of the <div> element that represents the menu, as well as changing the display property. The max-height value is being changed ...

I am struggling to get the pop-up to close using the current code. I suspect that the issue might be related to the variable I was previously using in WordPress. I have made changes but the pop-up

While delving deeper into the realm of Javascript, I encountered a stumbling block with a single popup intended for the main page of a WordPress website I am constructing. Despite my attempts to modify the code's variables, they seem unyielding. Surpr ...

Create a canvas and include input boxes in an HTML document

I'm attempting to create a canvas line diagonally above two textboxes that are also positioned diagonally (similar to Samsung's pattern passcode) when a button is clicked, but I am facing difficulties in achieving this. I have attempted to solve ...

What is the best way to apply a 2px padding to text-decoration: underline?

As a dedicated frontend developer, I believe in creating underlines with a 2px padding instead of the default 1px. Is there an easy solution for achieving this? PS: Yes, I am aware of using a div with a black background color and 1px * Npx with position: ...

Conceal the page's content as it moves beneath a stationary div

My issue involves a fixed div position with a margin from the top of the page. When I scroll my page, the content of my relatively positioned div (containing page content) is visible under the fixed div due to the margin from the top of the page. Despite s ...

Tips for applying color to a complete div within a fixed header while positioning the text in the center

I have a header with row elements that are filling it completely using the class "col-xs-2". I am trying to fill the color for one specific "col-xs-2" element and center the text within it. However, the color is only filling the "col-xs-2" div. Can someone ...

If a table column lacks an unspanned cell, IE will disregard its width

Here is a visual representation of the issue I am facing: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <body> <table border="1"> <colgroup> <col ...

IE11 React application cannot recognize the <main> tag

When using my React application, I encountered the following error message in the dev console while using IE11: Warning: The tag <main> is unrecognized in this browser. If you meant to render a React component, start its name with an uppercase let ...

Displaying a CSS span element as the topmost layer

I am struggling to get a tooltip to properly display on top of its parent element. Despite trying various combinations of z-index and overflow properties, I have not been able to achieve the desired outcome. The issue arises when hovering over the red box ...

Conceal the second click action within the anchor tag

Is there a way to hide the second click event on all anchor tags except those that trigger popupfun? I have a sample page set up. [Check out the JS Fiddle here][1] http://jsfiddle.net/ananth3087/LgLnpvf4/15/ Link Anchor Tags: The page includes two ...

PHP Verify that all variables contain no data

Looking for an efficient way to verify that all data submitted from a form to a PHP script is accurate. Code Snippet <?php $Name = $_POST['Name']; $ID = $_POST['ID']; $Submit = $_POST['submit']; $Reset = $_POST['rese ...

Ways to determine if an object has a provided attribute?

As I work on creating a small website using django, I encountered an issue: In my site, I want to view posts in detail, but not every post includes an image attribute - leading to errors when trying to display images that do not exist. The solution lies ...

I am looking to integrate a WordPress blog post into my Bootstrap website

Is there a way to showcase the 3 most recent posts from my WordPress blog (www.xyz.wordpress.com) on my Bootstrap HTML website without using PHP? Feedburner got me close, but I'm limited in CSS styles and don't want the "Headline by Feedburner" ...

What strategies can I use to encourage Frank to cooperate more smoothly with Cocoapods and interface-builder in Rubymotion?

I've been struggling all day to integrate Frank into my RubyMotion app. This process has been quite stressful, and I could really use some assistance. Here is what I have done so far: Created an app with Cocoapods and the ib gem. Installed the fran ...

Steps for designing image animations with fade in and fade out effects

I have a task to enhance the current code provided below, which currently works with only two images. HTML: <div id="cf"> <img class="bottom" src="<?php bloginfo('template_directory') ?>/assets/img/image1" /> <img class ...

A versatile JavaScript function built to efficiently validate numerous forms across a webpage

Sorry for the simple query, but I'm still learning JavaScript. I have a script that checks if a text field is empty to validate user inputs. If it's not empty, a confirmation window pops up before submitting the form and uploading the information ...

Is it possible to manipulate an image tag's image using only CSS?

Is it possible to hide an image from the src attribute of an <img> tag and instead set a background image on the tag using CSS? One idea could be adjusting the positioning or text-indent of the actual image to move it out of view, and then applying ...

Guide on How to Show Only the Initial Word of an H2 Header Using JavaScript or CSS

Is there a way to display only the first word from an h2 heading? For instance: In the website's source code, it would appear like this <h2> Stackoverflow is an Ideal Place</h2> But on the live website, it should be displayed like this ...

Moving the final item in the list to the end

I've chosen to implement the Vali Admin theme and am currently attempting to move the last list item in the left sidebar to the bottom. While I have limited experience with flexbox, I decided to change the menu to display: flex and followed the steps ...

Elements that possess identical class attributes yet exhibit dynamic behavior

I'm currently facing challenges with dynamically generated elements. I am working on a page for my website that will show a list of users (data provided by the controller). Each user is represented within a div, containing two h3 tags displaying the u ...