Mandar Patil
Mandar Patil

Reputation: 538

HTML5 Validation for numeric values

I have a simple html page with two input text boxes and a submit button. When I click on the submit button with invalid email address it gives me an error message. How can i implement the same(displaying a small tooltip like popup) for other text box for numeric values?

enter image description here

Here is the complete html

<html>
<head>
<style>
body {
  font: 1em sans-serif;
  padding: 0;
  margin : 0;
}

form {
  max-width: 200px;
  margin: 0;
  padding: 0 5px;
}

p > label {
  display: block;
}

input[type=text],
input[type=email],
input[type=number],
textarea,
fieldset {
/* required to properly style form 
   elements on WebKit based browsers */
  -webkit-appearance: none;

  width : 100%;
  border: 1px solid #333;
  margin: 0;

  font-family: inherit;
  font-size: 90%;

  -moz-box-sizing: border-box;
  box-sizing: border-box;
}

input:invalid {
  box-shadow: 0 0 5px 1px red;
}

input:focus:invalid {
  outline: none;
}
</style>

</head>
<body><form>
<p>
    <label for="t1">What's your age?</label>
    <input type="number" id="t1" name="age">
  </p>
<p>
    <label for="t2">What's your e-mail?</label>
    <input type="email" id="t2" name="email">
  </p>
<p>
    <button>Submit</button>
  </p>
</form>
</body>
</html>

Upvotes: 1

Views: 7790

Answers (5)

CormacDon108
CormacDon108

Reputation: 11

<input type="number" required >
<input type="submit" >

This worked for me

Upvotes: 1

Yash Kumar Verma
Yash Kumar Verma

Reputation: 9620

well using default validation with HTML can do it without efforts

<input type="number" required >
<input type="submit" >

Upvotes: 0

Pranavadurai
Pranavadurai

Reputation: 1030

A better solution is to use the pattern attribute, that uses a regular expression to match the input:

 <input type="text" pattern="\d*" />

\d is the regular expression for a number, * means that it accepts more than one of them.

Upvotes: 7

Prakhar Singh
Prakhar Singh

Reputation: 206

It can be achieve by the help of javascript.

<input type="text" oninput="this.value = this.value.replace(/[^0-9.]/g, ''); this.value = this.value.replace(/(\..*)\./g, '$1');" > 

I'm just skipping the non-numeric characters. user will only able to fill numeric data. Hope that's what you want.

Upvotes: 0

Hemant Kabra
Hemant Kabra

Reputation: 884

As you are already using HTML 5 numeric textbox, so you do not need to setup this kind of tooltip manually. If is there any validation error then this tooltip will be automatically displayed same like email.

It's a number textbox so it won't allow you to enter any another character, except numbers, so in this case you will not get any validation error. If you are setting up any limitation like minimum and maximum value, and if validation is not true then a tooltip will be displayed automatically.

You can check tooltip by setting up some number limitations on textbox. Hope this will help you.

Upvotes: 0

Related Questions