Trigger html5 validation without form post - html

I want to achieve something like this without form post, as it will redirect the page.
here is my code
<form>
<input type="number" step="any" min="0" required oninvalid="this.setCustomValidity('Please enter price with decimal format, eg x.xx .')">
<button type="submit">submit</button>
</form>
I've did some research it seems like it has to be triggered with form post. Possible to trigger the html5 validtion with jquery function button click ?

Set a custom validation message on input change and intercept the form submit event:
var form = document.querySelector('form'),
input = document.querySelector('#input-price');
input.addEventListener("change", function (event) {
if (!input.checkValidity() || !/^\d+(\.\d+)?$/.test(input.value)) {
input.setCustomValidity("Please enter price with decimal format, eg x.xx .");
} else {
input.setCustomValidity("");
}
});
form.addEventListener("submit", function (event) {
event.preventDefault();
});
<form>
<input id="input-price" type="number" step="any" min="0" required>
<input type="submit">
</form>
input.checkValidity() returns true when the input value is a number as in 2, .1 and 1e10. The regex test then filters the two last cases (.1 and 1e10) out.

the html5 “pattern” attribute doesn't work in all Browsers
the only way is to use JavaScript code
try this code
Html
<input id="amount" maxlength="7" type="text" />
javaScript
$("#amount").on("keyup", function(){
var valid = /^\d{0,4}(\.\d{0,3})?$/.test(this.value),
val = this.value;
if(!valid){
alert("Please enter price with decimal format, eg x.xx!");
this.value = val.substring(0, val.length - 1);
}
});
to avoid accepting invalid input when pasting text (idea of #le_m)
try this second solution :
html
<input id="amount" maxlength="7" type="text" />
JS
$("#amount").on("change paste keyup", function(){
var valid = /^\d*(\.\d*)?$/.test(this.value),
val = this.value;
if(!valid){
alert("Please enter price with decimal format, eg x.xx!");
this.value = val.substring(0, val.length - 7);
}
});
result :
http://jsfiddle.net/vY39r/866/

Related

Which input element that accept digits only and allows a limited number of characters

I am trying to implement an (zip code of my country) input field that only accept digits and limit the number of characters to 5.
Which html input type and attributes are more appropriate for this task ?
<input type="text" name="zipcode" pattern="[0-9]{5}" />
pattern="\d{5}" would also work. But make sure to re-check it in your target-script because form-elements can be manipulated.
A complete example (WITH JQUERY) for checking values on change or keyup in the .checkFieldNum values and on submit the form.
JS
function checkNum(value)
{
return value.match(/\d{5}/);
}
$(document).ready(function(){
// trigger if element-value with class="checkFieldNum" changes or key is pressed
$('.checkFieldNum').on('change keyup',function(event){
if(checkNum($(this).val()) === false)
{
$(this).css({background:'tomato'})
}
else
{
$(this).css({background:''})
}
})
// trigger if form should be submitted
$('.formClassForSubmit').on('submit',function(event){
event.preventDefault();
var goOn = true;
$('.checkFieldNum').each(function(){
if(checkNum($(this).val()) === false)
{
goOn = false;
alert($(this).attr('name') + ' has wrong value')
}
})
if(goOn === true)
{
// In this case, everything is OK and go on whatever you will do..
}
})
})
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form action="?" method="post" class="formClassForSubmit">
<input type="text" class="checkFieldNum" name="zipcode1" pattern="[0-9]{5}" />
<input type="text" class="checkFieldNum" name="zipcode2" pattern="\d{5}" />
<input type="submit" name="send" value="send" />
</form>
see https://jsfiddle.net/7hbj6a3e/3/
<input type="number" minlength="5" maxlength="5" name="zipcode" />
see https://www.w3schools.com/tags/tag_input.asp

Have an HTML input tag restrict a certain input

How do you make an HTML input tag that does not allow the input of 1. It could for instance type 2131 or 11, just not 1 by itself. I have tried using patternMismatch= "[1]{1}" but the website does not render a message.
You will have to check the value each time the user inputs something. On input, check if the value is 1, if so clear the input field.
Code:
let input = document.querySelector('input');
input.addEventListener('input', (e) => {
if (!input.value == "1") return;
input.value = "";
})
Try using input type="number" with a step of 1 and a min of 2, like so:
<form action="/action_page.php"><label for="points">Points:</label> <input type="number" id="points" name="points" step="1" min="2" /> <input type="submit" /></form>

Allow 2 decimal places in <input type="number">

I have a <input type="number"> and I want to restrict the input of the users to purely numbers or numbers with decimals up to 2 decimal places.
Basically, I am asking for a price input.
I wanted to avoid doing regex. Is there a way to do it?
<input type="number" required name="price" min="0" value="0" step="any">
Instead of step="any", which allows for any number of decimal places, use step=".01", which allows up to two decimal places.
More details in the spec: https://www.w3.org/TR/html/sec-forms.html#the-step-attribute
In case anyone is looking for a regex that allows only numbers with an optional 2 decimal places
^\d*(\.\d{0,2})?$
For an example, I have found solution below to be fairly reliable
HTML:
<input name="my_field" pattern="^\d*(\.\d{0,2})?$" />
JS / JQuery:
$(document).on('keydown', 'input[pattern]', function(e){
var input = $(this);
var oldVal = input.val();
var regex = new RegExp(input.attr('pattern'), 'g');
setTimeout(function(){
var newVal = input.val();
if(!regex.test(newVal)){
input.val(oldVal);
}
}, 1);
});
For currency, I'd suggest:
<div><label>Amount $
<input type="number" placeholder="0.00" required name="price" min="0" value="0" step="0.01" title="Currency" pattern="^\d+(?:\.\d{1,2})?$" onblur="
this.parentNode.parentNode.style.backgroundColor=/^\d+(?:\.\d{1,2})?$/.test(this.value)?'inherit':'red'
"></label></div>
See http://jsfiddle.net/vx3axsk5/1/
The HTML5 properties "step", "min" and "pattern" will be validated when the form is submit, not onblur. You don't need the step if you have a pattern and you don't need a pattern if you have a step. So you could revert back to step="any" with my code since the pattern will validate it anyways.
If you'd like to validate onblur, I believe giving the user a visual cue is also helpful like coloring the background red. If the user's browser doesn't support type="number" it will fallback to type="text". If the user's browser doesn't support the HTML5 pattern validation, my JavaScript snippet doesn't prevent the form from submitting, but it gives a visual cue. So for people with poor HTML5 support, and people trying to hack into the database with JavaScript disabled or forging HTTP Requests, you need to validate on the server again anyways. The point with validation on the front-end is for a better user experience. So as long as most of your users have a good experience, it's fine to rely on HTML5 features provided the code will still works and you can validate on the back-end.
Step 1: Hook your HTML number input box to an onchange event
myHTMLNumberInput.onchange = setTwoNumberDecimal;
or in the HTML code
<input type="number" onchange="setTwoNumberDecimal" min="0" max="10" step="0.25" value="0.00" />
Step 2: Write the setTwoDecimalPlace method
function setTwoNumberDecimal(event) {
this.value = parseFloat(this.value).toFixed(2);
}
You can alter the number of decimal places by varying the value passed into the toFixed() method. See MDN docs.
toFixed(2); // 2 decimal places
toFixed(4); // 4 decimal places
toFixed(0); // integer
Try this for allowing only 2 decimal in input type
<input type="number" step="0.01" class="form-control" />
Or Use jQuery as suggested by #SamohtVII
$( "#ELEMENTID" ).blur(function() {
this.value = parseFloat(this.value).toFixed(2);
});
I found using jQuery was my best solution.
$( "#my_number_field" ).blur(function() {
this.value = parseFloat(this.value).toFixed(2);
});
I had the same requirement but after checking all these answers I realized there is no inbuilt support to block users from typing a particular number of decimal points. step="0.01" is useful when validating the input for a decimal number but still it will not block users from typing any decimal. In my case, I wanted a solution which will prevent user from entering invalid decimal. So I created my own custom JavaScript function which will enforce user any decimal rule. There is a slight performance issue but for my scenario it is okay to have a very small delay to make sure that user is not typing invalid decimal places. It might be useful for someone who wanted to prevent user from typing invalid decimal value on the input.
You can use this solution with step="0.01" if you want. You can use the below function on your element oninput event. If performance is critical for you, then think to use this on onchange event rather than oninput. And please specify maximum number of decimal places allowed in the input in data-decimal attribute. it can have values from 0 to any number.
function enforceNumberValidation(ele) {
if ($(ele).data('decimal') != null) {
// found valid rule for decimal
var decimal = parseInt($(ele).data('decimal')) || 0;
var val = $(ele).val();
if (decimal > 0) {
var splitVal = val.split('.');
if (splitVal.length == 2 && splitVal[1].length > decimal) {
// user entered invalid input
$(ele).val(splitVal[0] + '.' + splitVal[1].substr(0, decimal));
}
} else if (decimal == 0) {
// do not allow decimal place
var splitVal = val.split('.');
if (splitVal.length > 1) {
// user entered invalid input
$(ele).val(splitVal[0]); // always trim everything after '.'
}
}
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="number" data-decimal="0" oninput="enforceNumberValidation(this)" placeholder="No decimal places" value="" />
<input type="number" data-decimal="2" oninput="enforceNumberValidation(this)" placeholder="2 decimal places" value="" />
<input type="number" data-decimal="5" oninput="enforceNumberValidation(this)" placeholder="5 decimal places" value="" />
I might use RegExp to identify invalid value but I have to revert the change in the input as well. So I decided to not use RegExp.
just adding step=".01", sorted my issue.
<input type="number" class="form-control" name="price" step=".01">
Use this code
<input type="number" step="0.01" name="amount" placeholder="0.00">
By default Step value for HTML5 Input elements is step="1".
I had a strange editing experience with some of these solutions. This seems to work pretty well from a user's perspective (only intervene when necessary):
function handleNumberChanged (e) {
const fixed = parseFloat(e.target.value).toFixed(2).toString()
if (fixed.length < parseFloat(e.target.value).toString().length)
e.target.value = fixed
}
This question has been already answer but you can allow decimals
with the step attribute.
you can read more about it here: Allow-decimal-values
This is the solution I've came up with which also stops the user from typing in more that 2 decimals, which a lot of the solutions mentioned above, don't protect against
html:
<input autocomplete="off" type="number" id="priceField" step=".01" min="0" onkeypress="return priceCheck(this, event);"
Javascript:
function priceCheck(element, event) {
result = (event.charCode >= 48 && event.charCode <= 57) || event.charCode === 46;
if (result) {
let t = element.value;
if (t === '' && event.charCode === 46) {
return false;
}
let dotIndex = t.indexOf(".");
let valueLength = t.length;
if (dotIndex > 0) {
if (dotIndex + 2 < valueLength) {
return false;
} else {
return true;
}
} else if (dotIndex === 0) {
return false;
} else {
return true;
}
} else {
return false;
}
}
Only 3 decimal point input value in textbox using Javascript.
<input type="text" class="form-control" onkeypress='return AllowOnlyAmountAndDot(this,event,true);/>
function AllowOnlyAmountAndDot(id, e, decimalbool) {
if(decimalbool == true) {
var t = id.value;
var arr = t.split(".");
var lastVal = arr.pop();
var arr2 = lastVal.split('');
if (arr2.length > '2') {
e.preventDefault();
}
}
}
<input type="number" class="form-control" id="price" oninput="validate(this)" placeholder="Enter price" name="price" style="width:50%;">
var validate = function(e) {
var t = e.value;
e.value = (t.indexOf(".") >= 0) ? (t.substr(0, t.indexOf(".")) + t.substr(t.indexOf("."), 3)) : t;
}
On Input:
<input type="number" name="price" id="price" required>
On script:
$('#price').on('change', function() {
var get_price = document.getElementById('price').value;
var set_price = parseFloat(get_price).toFixed(2);
$('input[name=price').val(set_price);
})
You can use this. react hooks
<input
type="number"
name="price"
placeholder="Enter price"
step="any"
required
/>
just write
<input type="number" step="0.1" lang="nb">
lang='nb" let you write your decimal numbers with comma or period
On input:
step="any"
class="two-decimals"
On script:
$(".two-decimals").change(function(){
this.value = parseFloat(this.value).toFixed(2);
});

HTML5 required attribute one of two fields

I have a form with two required input fields:
<form>
<input type="tel" name="telephone" required>
<input type="tel" name="mobile" required>
<input type="submit" value="Submit">
</form>
Is it possible to get browsers to validate so only one of them is required? i.e if telephone is filled, don't throw an error about mobile being empty and vice versa
Update 2020-06-21 (ES6):
Given that jQuery has become somewhat unfashionable in the JavaScript world and that ES6 provides some nice syntactic sugar, I have written a pure JS equivalent to the original answer:
document.addEventListener('DOMContentLoaded', function() {
const inputs = Array.from(
document.querySelectorAll('input[name=telephone], input[name=mobile]')
);
const inputListener = e => {
inputs
.filter(i => i !== e.target)
.forEach(i => (i.required = !e.target.value.length));
};
inputs.forEach(i => i.addEventListener('input', inputListener));
});
<form method="post">
Telephone:
<input type="tel" name="telephone" value="" required>
<br>Mobile:
<input type="tel" name="mobile" value="" required>
<br>
<input type="submit" value="Submit">
</form>
This uses the input event on both inputs, and when one is not empty it sets the required property of the other input to false.
Original Answer (jQuery):
I played around with some ideas and now have a working solution for this problem using jQuery:
jQuery(function ($) {
var $inputs = $('input[name=telephone],input[name=mobile]');
$inputs.on('input', function () {
// Set the required property of the other input to false if this input is not empty.
$inputs.not(this).prop('required', !$(this).val().length);
});
});
I've written a jQuery plugin wrapping the above JavaScript code so that it can be used on multiple groups of elements.
Based on Andy's answer, but I needed a checkbox implementation & came up with this.
what role(s) do you want?
<input type="checkbox" data-manyselect="roler" name="author" required>
<input type="checkbox" data-manyselect="roler" name="coder" required>
<input type="checkbox" data-manyselect="roler" name="teacher" required>
where will you work?
<input type="checkbox" data-manyselect="placement" name="library" required>
<input type="checkbox" data-manyselect="placement" name="home" required>
<input type="checkbox" data-manyselect="placement" name="office" required>
jQuery(function ($) {
// get anything with the data-manyselect
// you don't even have to name your group if only one group
var $group = $("[data-manyselect]");
$group.on('input', function () {
var group = $(this).data('manyselect');
// set required property of other inputs in group to false
var allInGroup = $('*[data-manyselect="'+group+'"]');
// Set the required property of the other input to false if this input is not empty.
var oneSet = true;
$(allInGroup).each(function(){
if ($(this).prop('checked'))
oneSet = false;
});
$(allInGroup).prop('required', oneSet)
});
});
Here for anyone else getting here by googling and wanting a quick solution for one of many checkboxes.
You would better do form data validation with Javascript anyway, because the HTML5 validation doesn't work in older browsers. Here is how:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Form Validation Phone Number</title>
</head>
<body>
<form name="myForm" action="data_handler.php">
<input type="tel" name="telephone">
<input type="tel" name="mobile">
<input type="button" value="Submit" onclick="validateAndSend()">
</form>
<script>
function validateAndSend() {
if (myForm.telephone.value == '' && myForm.mobile.value == '') {
alert('You have to enter at least one phone number.');
return false;
}
else {
myForm.submit();
}
}
</script>
</body>
</html>
.
Live demo here: http://codepen.io/anon/pen/LCpue?editors=100. Let me know if this works for you, if you will.
For two text fields #Andy's answer is working awesome, but in case of more than two fields we can use something like this.
jQuery(function ($) {
var $inputs = $('input[name=phone],input[name=mobile],input[name=email]');
$inputs.on('input', function () {
var total = $('input[name=phone]').val().length + $('input[name=mobile]').val().length + $('input[name=email]').val().length;
$inputs.not(this).prop('required', !total);
});
});

How can I create a custom message when an HTML5 required input pattern does not pass?

I have the following:
<input required pattern=".{6,}" class="big medium-margin" name="Password" placeholder="Password" size="25" type="password" />
When I enter just one character I get a message saying:
"Please match the requested format"
Is there a way I can customize this message to say something like "Please enter at least 5 characters"
You can do a quick and dirty way with this trick:
<form>
<label for="username">Username:</label><br/>
<input id="username" type="text" pattern=".{6,}" autofocus required title="Please enter at least 5 characters">
<input id="submit" type="submit" value="create">
</form>
Use: setCustomValidity
First function sets custom error message:
$(function(){
$("input[name=Password]")[0].oninvalid = function () {
this.setCustomValidity("Please enter at least 5 characters.");
};
});
Second function turns off custom message. Without this function custom error message won't turn off as the default message would:
$(function(){
$("input[name=Password]")[0].oninput= function () {
this.setCustomValidity("");
};
});
P.S. you can use oninput for all input types that have a text input.
For input type="checkbox" you can use onclick to trigger when error should turnoff:
$(function(){
$("input[name=CheckBox]")[0].onclick= function () {
this.setCustomValidity("");
};
});
For input type="file" you should use change.
The rest of the code inside change function is to check whether the file input is not empty.
P.S. This empty file check is for one file only, feel free to use any file checking method you like as well as you can check whether the file type is to your likes.
Function for file input custom message handling:
$("input[name=File]").change(function () {
let file = $("input[name=File]")[0].files[0];
if(this.files.length){
this.setCustomValidity("");
}
else {
this.setCustomValidity("You forgot to add your file...");
}
//this is for people who would like to know how to check file type
function FileType(filename) {
return (/[.]/.exec(filename)) ? /[^.]+$/.exec(filename) : undefined;
}
if(FileType(file.name)!="pdf"||FileType(file.name)!="PDF"){
this.setCustomValidity("Your file type has to be PDF");
//this is for people who would like to check if file size meets requirements
else if(file.size/1048576>2){
// file.size divided by 1048576 makes file size units MB file.size to megabytes
this.setCustomValidity("File hast to be less than 2MB");
}
else{
this.setCustomValidity("");
}
});//file input custom message handling function
HTML5 form required attribute. Set custom validation message?
JSFiddle: http://jsfiddle.net/yT3w3/
Non-JQuery solution:
function attachHandler(el, evtname, fn) {
if (el.addEventListener) {
el.addEventListener(evtname, fn.bind(el), false);
} else if (el.attachEvent) {
el.attachEvent('on' + evtname, fn.bind(el));
}
}
attachHandler(window, "load", function(){
var ele = document.querySelector("input[name=Password]");
attachHandler(ele, "invalid", function () {
this.setCustomValidity("Please enter at least 5 characters.");
this.setCustomValidity("");
});
});
JSFiddle: http://jsfiddle.net/yT3w3/2/
I'd add another attribute oninvalid.
oninvalid="setCustomValidity('Please enter at least 5 characters')"
<input required pattern=".{6,}" class="big medium-margin" name="Password" placeholder="Password" size="25" type="password" oninvalid="setCustomValidity('Please enter at least 5 characters')"/>
I found that, chrome at least, adds to the message the title of the input automatically, so no extra js is required, see this:
the input looks like this:
<input type="text" title="Number with max 3 decimals" pattern="^\d+(\.\d{1,3})?$">
It is very simple without javascript or jQuery validation. We can achieve it by HTML5
Let suppose we have HTML field:
<input required pattern=".{6,}" class="big medium-margin" name="Password" placeholder="Password" size="25" type="password" />
Just change the HTML as
<input required pattern=".{6,}" class="big medium-margin" title="Please enter at least 5 characters." name="Password" placeholder="Password" size="25" type="password" />
If you observe, just add title = "Error message"
Now whenever form will be post, the given messages will be appeared and we did not need JavaScript or jQuery check.
This solution works for me.
I simply use oninvalid to set the custom validty error message and then use onchange to reset the message so the form can submit.
<input type="number" oninvalid="this.setCustomValidity('Please enter an INTEGER')" onchange="this.setCustomValidity('')" name="integer-only" value="0" min="0" step="1">
You'd need to use the setCustomValidity function. The problem with this is that it'd only guarantee a custom message for users who have JavaScript enabled.
<input required pattern=".{6,}" ... oninput="check(this)">
^^^^^^^^^^^^^^^^^^^^^
function check (input) {
if (input.value.search(new RegExp(input.getAttribute('pattern'))) >= 0) {
// Input is fine. Reset error message.
input.setCustomValidity('');
} else {
input.setCustomValidity('Your custom message here.');
}
}
https://www.geeksforgeeks.org/form-required-attribute-with-a-custom-validation-message-in-html5/
<input id="gfg" type="number" min="101" max="999" required>
<button onclick="myFunction()">Try it</button>
<p id="geeks"></p>
<script>
function myFunction() {
var inpObj = document.getElementById("gfg");
if (!inpObj.checkValidity()) {
document.getElementById("geeks")
.innerHTML = inpObj.validationMessage;
} else {
document.getElementById("geeks")
.innerHTML = "Input is ALL RIGHT";
}
}
</script>