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>
);
}
Related
I need to make three textboxes with date of birth, amount (money) and interest.
with click on the button a overview of doubled amount should appear if I put my money on the bank at a certain interest rate.
I don't know how to start.
Textboxes:
Generally, for creating User Interface on the web, you will write HTML. Using your case, for example, we know you need three textboxes. I would use <input> elements like this:
Step 1
<input name="dob" type="date" />
<input name="amount" type="number" step="0.01" />
<input name="interest" type="number" step="0.001" />
Step 2
We can further wrap these to add text labels using <label> elements, like so:
<label>
Date of Birth
<input name="dob" type="date" />
</label>
<label>
Amount
<input name="amount" type="number" step="0.01" />
</label>
<label>
Interest
<input name="interest" type="number" step="0.001" />
</label>
Step 3
Then, to link them together, we wrap them using a <form> element:
<form>
<label>
Date of Birth
<input name="dob" type="date" />
</label>
<label>
Amount
<input name="amount" type="number" step="0.01" />
</label>
<label>
Interest
<input name="interest" type="number" step="0.001" />
</label>
</form>
Step 4
Finally, we need elements for calculation. I would use the aptly-named <output> element and a <button> element to submit the form:
<form>
<label>
Date of Birth
<input name="dob" type="date" />
</label>
<label>
Amount
<input name="amount" type="number" step="0.01" />
</label>
<label>
Interest
<input name="interest" type="number" step="0.001" />
</label>
<label>
Total
<output name="total">0</output>
</label>
<button type="submit">Calculate</button>
</form>
Calculation:
As you see above, <input> is an interactive element that generally has a name and value. value can be updated by someone using your page or via JavaScript, after the elements in question have been fully loaded. To update these elements and get values for your calculations via JavaScript, you would use something called the DOM (Document Object Model) and react to user input by "listening" to events (like "click", for example). The form fires an event called "submit" when you click the "Calculate" button in the example above. We can use that instead of "click", which makes it easier to handle everything inside the form (like the textboxes). For example:
// Step 1: Create a JavaScript function (actually gets run later)
const calcForm = form => {
// Get values (and totalElement) from form.elements
const {
amount: {value: amount},
interest: {value: interest},
total: totalElement,
} = form.elements
// Update the totalElement with interest * amount
totalElement.value = (interest * amount).toFixed(2)
}
// Step 2: Wait for the DOM to fully load (so formElement exists)
window.addEventListener('DOMContentLoaded', (event) => {
// Step 3: Get form element using the "js-form" class
const formElement = document.querySelector('.js-form')
// Step 4: Run calcForm on "submit" event
formElement.addEventListener('submit', (e) => {
e.preventDefault()
calcForm(e.target)
})
// Step 5: Run calcForm at start
calcForm(formElement)
})
One helpful thing to do is use classes as JavaScript "hooks", so I also changed the form HTML to read: <form class="js-form"> at this step. I use js- prefixes on classes to make it clear where it is used (that is, not CSS). You'll notice the line that says document.querySelector('.js-form')...this is what gets the <form> as an object in JavaScript.
Finally, putting all of this together, here's a working snippet with some basic (fully optional) CSS styling, but:
const calcForm = form => {
const {
amount: {value: amount},
interest: {value: interest},
total: totalElement,
} = form.elements
totalElement.value = (amount * interest).toFixed(2)
}
window.addEventListener('DOMContentLoaded', (event) => {
const formEl = document.querySelector('.js-form')
formEl.addEventListener('submit', (e) => {
e.preventDefault()
calcForm(e.target)
})
calcForm(formEl)
})
.form {
display: grid;
margin: 0 auto;
width: min-content;
justify-items: end;
text-align: right;
gap: 1rem;
}
.form__label {
display: grid;
gap: 0.5rem;
font-weight: bold;
}
.form__input {
width: 150px;
text-align: inherit;
}
<form class="js-form form">
<label class="form__label">
Date of Birth
<input class="form__input" name="dob" type="date" />
</label>
<label class="form__label">
Amount
<input class="form__input" name="amount" type="number" step="0.01" value="50.00" />
</label>
<label class="form__label">
Interest
<input class="form__input" name="interest" type="number" step="0.001" value="0.025" />
</label>
<label class="form__label">
Total
<output name="total">0</output>
</label>
<button type="submit">Calculate</button>
</form>
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>
How do I check multiple variable inputs at once to ensure that the regex is working? Everytime I enter anything, the form submits and doesn't alert anything.
I have tried test()method of regex validation too, and still no luck.
I am trying to validate user input with the following regex that makes to where anything that is not a number or blank space is considered a wrong input.
var format=/^(\s*|\d+)$/;
It only accepts numbers and blank spaces in the text box.
The following javascript is what I have:
var pitch = document.getElementById("pitch");
var chisel = document.getElementById("chis");
var saw = document.getElementById("saw");
//var arguments = [chisel, saw, pitch];
var format = /^(\s*|\d+)$/;
function regexTest() {
if (!chisel.match(format) && !saw.match(format) && !pitch.match(format)) {
alert("Repressed Action");
return false;
} else {
alert('Thank you');
}
}
<div class="lab">
<form method="post" action="http://weblab.kennesaw.edu/formtest.php">
Chisels: <input type="text" name="chisels" id="chis" size="5" /> Saw: <input type="text" name="saw" id="saw" size="5" /> Pitchfork: <input type="text" name="pitchfork" id="pitch" size="5" />
<br /> Customer Name: <input type="text" name="customer name" size="25" />
<br /> Shipping Address: <input type="text" name="shipping address" size="25" />
<br /> State:
<input type="radio" id="master" name="card" value="master" /><label for="master">MasterCard</label>
<input type="radio" id="american" name="card" value="american" /><label for="american">American Express</label>
<input type="radio" id="visa" name="card" value="visa" /><label for="visa">Visa</label>
<br />
<input type="reset" value="Reset" />
<div class="lab">
<button onclick="regexTest()">Submit</button>
<button onclick="return false">Cancel</button>
</div>
There are a number of issues with your code, below I've refactored it to be a bit easier to read and so it works.
The validation listener should be on the form's submit handler, not the submit button since forms can be submitted without clicking the button. Also, if you pass a reference to the form to the listener, it's much easier to access the form controls by name.
You should get the values of the form controls when the submit occurs, not before. Your code gets the values immediately, before the user has done anything (and possibly before the form even exists), so put that code inside the listener function.
Lastly, the regular expression needs to match anything that isn't a space or digit, so:
/[^\s\d]/
seems appropriate. However, this will still allow the form to submit if the fields are empty (they don't contain non-digits or non-spaces). You'll need to add a test for that.
function regexTest(form) {
// Get values when the function is called, not before
var pitch = form.pitchfork.value;
var chisel = form.chisels.value;
var saw = form.saw.value;
// Test for anything that's not a space or digit
// var format = /^(\s*|\d+)$/;
var format = /[^\s\d]/;
if (format.test(chisel) || format.test(pitch) || format.test(saw)) {
// There must be at least one non-space or non-digit in a field
alert("Repressed Action");
return false;
} else {
alert('Thank you');
// return false anyway for testing
return false;
}
}
<div class="lab">
<form onsubmit="return regexTest(this)">
Chisels: <input type="text" name="chisels" id="chis" size="5"><br>
Saw: <input type="text" name="saw" id="saw" size="5"><br>
Pitchfork: <input type="text" name="pitchfork" id="pitch" size="5"><br>
Customer Name: <input type="text" name="customer name" size="25"><br>
Shipping Address: <input type="text" name="shipping address" size="25">
<br> State:
<select name="states">
<option>Florida</option>
<option>Georgia</option>
<option>Alabama</option>
</select>
<br>
<input type="radio" id="master" name="card" value="master"><label for="master">MasterCard</label>
<input type="radio" id="american" name="card" value="american"><label for="american">American Express</label>
<input type="radio" id="visa" name="card" value="visa"><label for="visa">Visa</label>
<br>
<input type="reset" value="Reset">
<div class="lab">
<button>Submit</button>
<button onclick="return false">Cancel</button>
</div>
Hopefully this gets you to the next step.
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/
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" />