I want to setup validation in jQuery. It's not working, what should I do on submit button and jQuery code?
function validate() {
var total = $('#total').val();
var limit = 1000;
if (total > limit) {
alert('numbers cannot exceed the limit');
return false;
} else {
// submit
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="total"></input>
<input type="submit" value="Submit" onclick="validate()">
As #Devsi Odedra comment, you should parse the value to number to be able to compare instead of comparing string as well.
$('#total').keypress(function(event) {
if ((event.which != 46 || $(this).val().indexOf('.') != -1)
&& (event.which < 48 || event.which > 57)) {
event.preventDefault();
}
});
function validate() {
var total = parseFloat($('#total').val());
var limit = 1000;
if(total > limit) {
alert('numbers cannot exceed the limit');
return false;
} else {
// submit
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="total"></input> and submit button <input type="submit" value="Submit" onclick="validate()">
Updated
You should validate to only allow input float number like this
$('#total').keypress(function(event) {
if ((event.which != 46 || $(this).val().indexOf('.') != -1) && (event.which < 48 || event.which > 57)) {
event.preventDefault();
}
});
you should use button type instead of submit because submit must be use under the form tag
function validate() {
var total = $('#total').val();
var limit = 1000;
if (total > limit) {
alert('numbers cannot exceed the limit');
return false;
} else {
// submit
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="total"></input>
<input type="button" value="Submit" onclick="validate()">
Related
i have javascript that validate every user input and only allow character to be inputed in input text.
my issue is im using input text with no submit button (search form). my javascript doesn't allow hotkey enter, here my code :
function getkey(e)
{
if (window.event)
return window.event.keyCode;
else if (e)
return e.which;
else
return null;
}
function angkadanhuruf(e, goods, field)
{
var angka, karakterangka;
angka = getkey(e);
if (angka == null) return true;
karakterangka = String.fromCharCode(angka);
karakterangka = karakterangka.toLowerCase();
goods = goods.toLowerCase();
// check goodkeys
if (goods.indexOf(karakterangka) != -1)
return true;
// control angka
if ( angka==null || angka==0 || angka==8 || angka==9 || angka==27 )
return true;
if (angka == 13) {
var i;
for (i = 0; i < field.form.elements.length; i++)
if (field == field.form.elements[i])
break;
i = (i + 1) % field.form.elements.length;
field.form.elements[i].focus();
return false;
};
// else return false
return false;
}
<div class="search-box" style="margin-top: 20px;">
<form method="POST" id="searchform" action="search.html" >
<input name="kata" type="text" placeholder=" " onKeyPress="return angkadanhuruf(event,'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789#.-_',this)"/>
</form>
</div>
Hi i am trying to restrict user to input 2 digit number after the decimal.The below functionality is working but i am not able to modify the last two digit.suppose I have entered number 3456.78 and i want to modify 3456.68 it is not allowing.
$('.PMT_AMT').keypress(function(event) {
var $this = $(this);
if ((event.which != 46 || $this.val().indexOf('.') != -1) &&
((event.which < 48 || event.which > 57) &&
(event.which != 0 && event.which != 8))) {
event.preventDefault();
}
var text = $(this).val();
if ((event.which == 46) && (text.indexOf('.') == -1)) {
setTimeout(function() {
if ($this.val().substring($this.val().indexOf('.')).length > 3) {
$this.val($this.val().substring(0, $this.val().indexOf('.') + 3));
}
}, 1);
}
if ((text.indexOf('.') != -1) &&
(text.substring(text.indexOf('.')).length > 2) &&
(event.which != 0 && event.which != 8) &&
($(this)[0].selectionStart >= text.length - 2)) {
event.preventDefault();
}
});
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<input type="text" class="PMT_AMT">
Here's one possibility that uses a regular expression. Save the old input value on keypress, and if the new value on keyup does not validate, reset to that old value.
You need to validate on keypress as well, because otherwise, if the user types very fast, an invalid value can be saved:
const re = /^\d+(\.\d{0,2})?$/;
let oldVal;
$('.PMT_AMT').keypress(function(event) {
const { value } = this;
if (re.test(value)) oldVal = value;
});
$('.PMT_AMT').keyup(function(event) {
const newVal = this.value;
if (!re.test(newVal)) this.value = oldVal;
});
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<input type="text" class="PMT_AMT">
This solution creates a prediction and tests the regular expression against that instead.
$('.PMT_AMT').keypress(function(event) {
if(!/^\d*(\.\d{0,2})?$/.test(
this.value.slice(0, this.selectionStart)
+ String.fromCharCode(event.which)
+ this.value.slice(this.selectionEnd)
)) event.preventDefault();
});
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<input type="text" class="PMT_AMT">
Why use jQuery and not just browser functionality?
<input type="number" step="0.01">
On submit the browser will check if the submitted value of the input field has maximum two decimals.
Here is the fiddle which will allow only to numbers.
I want to do this in based on id.
So i created this fiddle
$(document).ready(function () {
//called when key is pressed in textbox
$("#quantity").keypress(function (e) {
//if the letter is not digit then display error and don't type anything
if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) {
//display error message
$("#errmsg").html("Digits Only").show().fadeOut("slow");
return false;
}
});
});
How can i do this for a series of id like quantity1,quantity2, like this..
Update :
I can't use class name.. How can i do it only by id
All you've to do is to match all the id's which is simple. See this fiddle.
Here's the part code -
$(document).ready(function () {
//called when key is pressed in textbox
$("[id^=quantity]").keypress(function (e) {
//if the letter is not digit then display error and don't type anything
if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) {
//display error message
$("#errmsg").html("Digits Only").show().fadeOut("slow");
return false;
}
});
});
Demo
Try this
HTML
Number : <input type="text" name="quantity" class= "numberonly" id="quantity1" />
Number1 : <input type="text" name="quantity" class= "numberonly" id="quantity2" />
Number1 : <input type="text" name="quantity" class= "numberonly" id="quantity3" />
<span id="errmsg"></span>
Jquery
$(document).ready(function () {
for(var i = 1; i< 4 ;i++)
{
//called when key is pressed in textbox
$("#quantity"+i).keypress(function (e) {
//if the letter is not digit then display error and don't type anything
if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) {
//display error message
$("#errmsg").html("Digits Only").show().fadeOut("slow");
return false;
}
});
}
});
How can I restrict entering special characters in the text box (txt_edition) by editing below code for validation? I want only numbers to be entered.
<script>
function validateForm()
{
var x = document.forms["frm_bokAdd"]["txt_edition"].value;
if (x==null || x=="")
{
alert("Edition must be filled out");
return false;
}
</script>
Below is my form
<form name="frm_bokAdd" action ="#" method="post" onsubmit="return validateForm()" >
<table border="0" align="center">
<tr><td> <input type="text" name="txt_edition" ></td></tr>
<tr><td> <input type="submit" name="bookIns_submit" value="Add"></td></tr>
</table>
</form>
can use this
HTML
<input type="text" onkeypress="return isNumber(event)" >
JS(at end of Body )
function isNumber(evt) {
var charCode = (evt.which) ? evt.which : event.keyCode
if (charCode > 31 && (charCode < 48 || charCode > 57)) {
return false;
}
return true;
}
DEMO is Here
How can I restrict entering special characters in the text box (txt_edition)
Don't. Allow users to arrive at a valid value any way they like, you really only care that the value is valid when it's sent to the server, and even then you should validate there too.
by editing below code for validation? I want only numbers to be entered.
Just test when the form is submitted, passing a reference to the form in the call:
<form ... onsubmit="return validateForm(this)" >
and the function:
function validateForm(form) {
var value = form.txt_edition.value;
if (/\D/.test(value) || value == '') {
alert("Edition must be filled out and contain only numbers");
return false;
}
}
use regex.
if (x.match(/^[0-9]*\.[0-9]*$/) !== null) {
//text is only numbers (use /^[0-9]*$/ for integers)
}
Try it
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<style type="text/css">
body
{
font-size: 9pt;
font-family: Arial;
}
</style>
</head>
<body>
Alphanumeric value:
<input type="text" id="text1" onkeypress="return IsAlphaNumeric(event);" ondrop="return false;"
onpaste="return false;" />
<span id="error" style="color: Red; display: none">* Special Characters not allowed</span>
<script type="text/javascript">
var specialKeys = new Array();
specialKeys.push(8); //Backspace
specialKeys.push(9); //Tab
specialKeys.push(46); //Delete
specialKeys.push(36); //Home
specialKeys.push(35); //End
specialKeys.push(37); //Left
specialKeys.push(39); //Right
function IsAlphaNumeric(e) {
var keyCode = e.keyCode == 0 ? e.charCode : e.keyCode;
var ret = ((keyCode >= 48 && keyCode <= 57) || (keyCode >= 65 && keyCode <= 90) || (keyCode >= 97 && keyCode <= 122) || (specialKeys.indexOf(e.keyCode) != -1 && e.charCode != e.keyCode));
document.getElementById("error").style.display = ret ? "none" : "inline";
return ret;
}
</script>
</body>
</html>
Try to use regular expression -
var edition = document.getElementById('txt_edition').value;
outputVal = edition.replace(/[^0-9a-zA-Z]/g,"");
if (edition != outputVal) {
return false;
}
You can restrict the key press like below,
function restrict_letters(e) {
var keyCode = e . keyCode == 0 ? e . charCode : e . keyCode;
// only 0 to 9
if (keyCode < 48 && keyCode > 57) {
return false;
}
}
you can get more key codes in here.
Also change the html function call like below,
<input type="text" onkeypress="return restrict_letters(event)">
Note: function call need to give for the input field not for the form submit.
To allow user to enter only number and dot. Use this regular expression
function NumAndTwoDecimals(event , obj){
reg = /[^0-9.,]/g;
obj.value = obj.value.replace(reg,"");
}
SEE DEMO HERE
HTML code is
<input id="txtId" type="text" onkeyup="NumAndTwoDecimals(event , this);"></input>
To restrict user to enter only two number after '.' operator use
function NumAndTwoDecimals(e , field) {
var val = field.value;
var re = /^([0-9]+[\.]?[0-9]?[0-9]?|[0-9]+)$/g;
var re1 = /^([0-9]+[\.]?[0-9]?[0-9]?|[0-9]+)/g;
if (re.test(val)) {
//do something here
} else {
val = re1.exec(val);
if (val) {
field.value = val[0];
} else {
field.value = "";
}
}
}
SEE DEMO HERE
I want to allow only alphabets in textbox using JavaScript
I used the code:
var nam=f.nm.value;
if(!isNaN(nam))
region.innerHTML="alphabets only";
It is not working and allows numbers as well. How can i fix this?
<html>
<head>
<title>allwon only alphabets in textbox using JavaScript</title>
<script language="Javascript" type="text/javascript">
function onlyAlphabets(e, t) {
try {
if (window.event) {
var charCode = window.event.keyCode;
}
else if (e) {
var charCode = e.which;
}
else { return true; }
if ((charCode > 64 && charCode < 91) || (charCode > 96 && charCode < 123))
return true;
else
return false;
}
catch (err) {
alert(err.Description);
}
}
</script>
</head>
<body>
<table align="center">
<tr>
<td>
<input type="text" onkeypress="return onlyAlphabets(event,this);" />
</td>
</tr>
</table>
</body>
</html>
just use onkeypress event like below:
<input type="text" name="onlyalphabet" onkeypress="return (event.charCode > 64 && event.charCode < 91) || (event.charCode > 96 && event.charCode < 123)">
From kosare comments, i have create an demo http://jsbin.com/aTUMeMAV/2/
HTML
<form name="f" onsubmit="return onlyAlphabets()">
<input type="text" name="nm">
<div id="notification"></div>
<input type="submit">
</form>
javascript
function onlyAlphabets() {
var regex = /^[a-zA-Z]*$/;
if (regex.test(document.f.nm.value)) {
//document.getElementById("notification").innerHTML = "Watching.. Everything is Alphabet now";
return true;
} else {
document.getElementById("notification").innerHTML = "Alphabets Only";
return false;
}
}
You can use HTML5 pattern attribute to do this:
<form>
<input type='text' pattern='[A-Za-z\\s]*'/>
</form>
If the user enters an input that conflicts with the pattern, it will show an error dialogue automatically.
You can try:
function onlyAlphabets(e, t) {
return (e.charCode > 64 && e.charCode < 91) || (e.charCode > 96 && e.charCode < 123) || e.charCode == 32;
}
:::::HTML:::::
<input type="text" onkeypress="return lettersValidate(event)" />
Only letters no spaces
::::JS::::::::
// ===================== Allow - Only Letters ===============================================================
function lettersValidate(key) {
var keycode = (key.which) ? key.which : key.keyCode;
if ((keycode > 64 && keycode < 91) || (keycode > 96 && keycode < 123))
{
return true;
}
else
{
return false;
}
}