I would like to validate an input date with a null value like this
<input type="date" value="0000-00-00" id="date" />
On submit I have a this logical message 'Please enter a date.'
I found something like this http://jsfiddle.net/trixta/zRGd9/embedded/result,html,js,css/.
If you know how to do this, here is a sample http://jsfiddle.net/zRGd9/24/
This is simply not a date and depending of the browser implementation this value is either emptied or considered a badInput or a typeMismatch.
If you want to use this you have the following options:
Strictly empty it yourself:
$('input[type="date"]')
.on('change.empty', function () {
var val = $.prop(this, 'value');
if (!val || val == '0000-00-00') {
$.prop(this, 'value', '');
}
})
.trigger('change.empty')
;
Set a novalidate attribute:
```
<form novalidate="">
<!-- ... -->
</form>
Use a different input if you also want to allow non valid date:
```
<input type="number" min="0" max="31" />
<input type="number" min="0" max="12" />
<input type="number" min="0" max="9999" />
Related
How can I set the maxlength attribute in my text input field equal to the value the user enters in the number input field in the same form?
<form action="/action_page.php">
<input id="number" type="number" value="20" max="40">
<input type="text" id="username" name="username" maxlength="10"><br><br>
<input type="submit" value="Submit">
</form>
I'm guessing this maybe requires JavaScript?
You can set the maxlength property on the input event.
document.querySelector("#number").addEventListener("input", function(e){
document.querySelector("#username").maxLength = this.value;
});
<form>
<input id="number" type="number" value="20" max="40">
<input type="text" id="username" name="username" maxlength="20"><br><br>
<input type="submit" value="Submit">
</form>
Yes, this requires JavaScript. You would do something like this:
document.querySelector('#number').addEventListener('input', (e) => {
e.target.closest('form').querySelector('[name="username"]').maxLength = e.target.value;
});
JSFiddle: https://jsfiddle.net/63cpv8rk/
Here, we add an event handler for the input event for the element selected by #number. (You should avoid using these ID attributes though... they clutter up the global scope needlessly.)
Then on input, we find the parent form, and then select the input by name. Finally, we set its max length to the value that was just put in our field.
I currently have an input type="text" that I transform into a currency value on the "keyup" event. In order to keep this functionality (works fine), the input type has to be set to "text". At the same time, I would like to have a minimum value of "100.00" set to it.
Any way I can accomplish this? Also, would I able to customize my jquery validation message to say "Minimum Amount $100.00"?
$('input.number').keyup(function(event) {
$(this).val(function(index, value) {
return value
.replace(/\D/g, "")
.replace(/([0-9])([0-9]{2})$/, '$1.$2')
.replace(/\B(?=(\d{3})+(?!\d)\.?)/g, ",");
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input required id="balance" name="balance" type="text" class="number" />
You can add this property in your input filed: minlength="5"
<input required id="balance" name="balance" type="text" class="number" minlength="5" />
And in your JS code you can add a 'if' statement to check that this input contain at least 5 char.
Furthermore you can add the same 'if' statement in your back-end to check it again.
Thank you all for your input.
I've ended up keeping the input type="text" for the number of digits users can type in and called a function to check the input value against the 100.
function checkAmount() {
var valueBalance = $("#balance").val();
var valueNumberBalance = parseFloat((valueBalance).replace(/[^\d\.]/, ''));
if (valueNumberBalance < 100) {
$("#balance").get(0).setCustomValidity("Minimum Amount of $100.00");
}
else {
$("#balance").get(0).setCustomValidity("");
}
}
A snippet created using the type="number" instead of type="text" on the input still allows the jQuery functionality to work.
The validation message is HTML5 and not jQuery as you did not provide that code. I did the following:
Changed to type="number"
Added min="100"
Added step="0.01" to handle currency stepping
$('input.number').keyup(function(event) {
$(this).val(function(index, value) {
return value
.replace(/\D/g, "")
.replace(/([0-9])([0-9]{2})$/, '$1.$2')
.replace(/\B(?=(\d{3})+(?!\d)\.?)/g, ",");
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
Text input (original): <input required id="balance" name="balance" class="number" type="text" /><br />
Number input: <input required id="balance" name="balance" class="number" type="number" min="100" max="99999" step="0.01" /><br />
<input type="submit" />
<small>Enter less than 100 and press 'submit' to see validations.</small>
</form>
you can try to currency validation using regex
<div class="col-sm-3 form-group">
<b>Premium :*</b><br>
<p><input type="text" class="form-control" oninput="this.className = ''" name="premium" id="premium" valideAtt="currency" title="Premium" onblur="defaultValidation(this)"></p>
<span id="er_premium" style="display: block; width:100%; float: left;"></span>
</div>
<script type="text/javascript">
var REG_CURRENCY = /(?=.*\d)^\$?(([1-9]\d{0,2}(,\d{3})*)|0)?(\.\d{1,2})?$/;
function defaultValidation(src){
var getAttributeValue=src.attributes.valideAtt.value;
if(getAttributeValue=="currency"){
if(!src.value.match(REG_CURRENCY)){
$("#"+src.id).addClass("invalid");
$("#er_"+src.id).html("<span style=\"color:red\">Please Enter Valide currency Value.<\span>");
return false;
}else{
$("#er_"+src.id).html("");
return true;
}
}
}
<script>
I wrote a code to validate a form on client-side. Since I binded all the error messages on('input', function()) now the last case to take in consideration is when the user didn't even hit a required input leaving it empty.
If all the inputs in the form were required I could have used something like
$('#subButton').on('click', function(e) {
if (!$('#formName').val()) {
e.preventDefault();
alert("Fill all the required fields");
});
But since in my form there are required inputs (with class="req") and non required inputs, I would like to know if there's a method to perform the check only on the .req inputs.
Something like:
$('#subButton').on('click', function(e) {
if (!$('#formName.req').val()) {
e.preventDefault();
alert("Fill all the required fields");
}
});
In other words I would like to perform the identical check which the up-to-date browsers do if the HTML required option is specified, just to be sure that, if the browser is a bit old and doesn't "read" the required option, jQuery prevents the form to be sent.
Just use .filter and check the length. Also, a simple ! check probably isn't good, what if someone enters 0?
var hasEmptyFields = $('#formName.req').filter(function() {
return this.value.replace(/^\s+/g, '').length; //returns true if empty
//Stole the above regex from: http://stackoverflow.com/questions/3937513/javascript-validation-for-empty-input-field
}).length > 0
if (hasEmptyFields) {
}
Use reduce
const submitAllowed = $('.req').toArray().reduce((result, item) => {
return result && (!!item.value || item.value === 0);
}, true)
if (!submitAllowed) { ... }
Here is a simple demo:
<form action="dummy.asp" onSubmit="return handleSubmit()">
<p> You can only submit if you enter a name </p>
<br />
Enter name: <input class="req" type="text" name="fname">
<input type="submit" value="Submit">
</form>
<script>
function handleSubmit() {
const submitAllowed = $('.req').toArray().reduce((result, item) => {
return result && (!!item.value || item.value === 0);
}, true)
return submitAllowed;
}
</script>
But since in my form there are required inputs (with class="req")
and non required inputs, I would like to know if there's a method to
perform the check only on the .req inputs
There is an HTML5 form boolean attribute required.
required works on:
<input type="text" />
<input type="search" />
<input type="url" />
<input type="tel" />
<input type="email" />
<input type="password" />
<input type="date" />
<input type="number" />
<input type="checkbox" />
<input type="radio" />
<input type="file" />
Example:
input {
display: block;
margin: 6px;
}
<form action="http://www.stackoverflow.com/">
<input type="text" placeholder="This is required" required />
<input type="text" placeholder="This isn't required" />
<input type="text" placeholder="This is required" required />
<input type="text" placeholder="This isn't required" />
<input type="submit" value="Press Me Without Filling in any of the Fields">
</form>
Peculiarly, the StackOverflow Snippet above doesn't seem to be working.
Here's a JSFiddle to demonstrate what it should be doing:
https://jsfiddle.net/a5tvaab8/
In this hypothetical page I have these inputs:
<input type="number" min=1 max=9 required />
<input type="number" min=1 max=9 required />
<input type="number" min=1 max=9 required />
<input type="number" min=1 max=9 required />
The that's confusing me is I know that they're restricted if I put the inputs in a form and submit the form.
But if you go to the fiddle: Fiddle
You can easily type in 100 or -20 or anything out side of the range of 1-9.
Is there a way to restrict the values in an input field at the time of inputting them? / without submitting it
(side questions: when do the min/max attributes of the input fields take effect? is it only at the time of submitting the form? Is it possible to validate the values without submitting a form?)
It looks like Google Chrome will enforce the min/max values when you use a submit button on the form.
I've updated your sample, with 3 submit buttons (labelled accordingly)... one will enforce the validation, the others will show the errors, but submit anyway.
http://jsfiddle.net/uatxcvzp/12/
<form>
<input type="number" min="1" max="9" required />
<input type="number" min="1" max="9" required />
<input type="number" min="1" max="9" required />
<input type="number" min="1" max="9" required />
<br/>
<br/><input type="button" value="Submit With No Forced Validation" onclick="this.form.submit();"/>
<br/><input type="submit" value="Submit With No Forced Validation" onclick="this.form.submit();"/>
<br/><input type="submit" value="Submit With Forced Validation"/>
</form>
In Firefox, the validation occurs on field blur, highlighting the field border in red and showing a tooltip explaining the error on hover. Using either submit style will halt and require that the errors are fixed.
In IE10, only the native submit button will force validation when you try to submit the form.
In Safari on iOS9.1, it looks like it is completely ignored regardless of the submit button/code style used. :-(
try this:
$("input[type='number']").change(function() {
var $this = $(this);
var val = $this.val();
var span = $(".error");
if (val > 9 || val < 1) {
span.text("value must be between 1 and 9");
}else{
span.text("");
}
});
input {
width: 40px;
height: 40px;
font-size: 1.4em;
}
.error {
color: red;
font-style: italic;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<input type="number" min=1 max=9 required />
<input type="number" min=1 max=9 required />
<input type="number" min=1 max=9 required />
<input type="number" min=1 max=9 required />
<span class="error"></span>
you can try the following code:
<input type="number" min=1 max=9 required onKeyDown="if(this.value.length==1) return false;" />
thy this its work for me
<input type="text" name="number" minlength='1' maxlength="9" required>
It looks like it's not natively possible as an uncontrolled component and it needs to become a controlled component - either writing javascript/jQuery manually, or using a library.
If using React, you can use something like react-hook-form and the code would look something like below. Specifically, see the age input.
Full documentation is here: https://react-hook-form.com/api/useform/register
import * as React from "react";
import { useForm } from "react-hook-form";
export default function App() {
const { register, handleSubmit } = useForm({
defaultValues: {
firstName: '',
lastName: '',
age: '',
}
});
return (
<form onSubmit={handleSubmit(console.log)}>
<input {...register("firstName", { required: true })} placeholder="First name" />
<input {...register("lastName", { minLength: 2 })} placeholder="Last name" />
<input
{...register("age", {
validate: {
positive: v => parseInt(v) > 0,
lessThan200: v => parseInt(v) < 200,
}
})}
/>
<input type="submit" />
</form>
);
}
I have two input fields and i am wondering how do i compare value's between these two fields.
<input id="start" type="numeric" value="" />
<input id="end" type="numeric" value="" />
In above input fields, if the value in input field with id='start' is greater than id='end', i want to display an alert.
I tried below but not working
if ($("#end").val() > $("#start").val()) {
//do something
}else {
alert('Wrong Input');
}
What am i doing wrong???
You should bind an event handler such as 'keypress' to one of the fields. When that even is triggered, you should compare the values of both the input fields and show alert if necessary.
Additionally, type="number" is correct not "numeric" .
Here's a working fiddle-
http://jsfiddle.net/pe2ZE/
Use type="number", As per my knowledge there is type as such numeric
Code
if (+$("#end").val() > +$("#start").val()) {
//do something
} else {
alert('Wrong Input');
}
Here I have use + to convert value to integer
you are comparing strings $("#end").val() > $("#start").val() so you have to compare in numbers, and dont forget about the radix
if(parseInt($("#end").val(),10) > parseInt($("#start").val(),10))
and type="numeric" is a wrong syntax, use type="number"
<input id="start" type="number" value="" />
You need to use type="number" to make the script work:
<input id="start" type="number" value="" />
<input id="end" type="number" value="" />
Demo
Or you can use input type text and then parse the input using parseInt(val) and compare them. somethink like this:
if (parseInt($("#end").val()) > parseInt($("#start").val())){
//rest code
}
you can't use type="numeric" to make input numeric only
to solve this proplem use this code
HTML
<input type="tel" name="name">
jQuery
// HTML Text Input allow only Numeric input
$('[type=tel]').on('change', function(e) {
$(e.target).val($(e.target).val().replace(/[^\d\.]/g, ''))
})
$('[type=tel]').on('keypress', function(e) {
keys = ['0','1','2','3','4','5','6','7','8','9','.']
return keys.indexOf(event.key) > -1
})
You have to type cast the value to int just like
if (parseInt($("#end").val()) > parseInt($("#start").val())) {
//do something
}else {
alert('Wrong Input');
}