function alphaOnly(event) {
var key = event.keyCode;
return ((key >= 8 && key <= 47) || (key >= 65 && key <= 222));
};
My function is not able to print # # $ % & ! * ( )
I could not find key codes for the above symbols. Please help me to accept these characters.
You can use regular expression instead on checking ascii values :
<script type="text/javascript">
function alphaOnly() {
var isValid = false;
var regex = /^[a-zA-Z%*#]*$/;
isValid = regex.test($("#field").val());
return isValid;
}
</script>
Related
I'm using the following JavaScript + Regex to auto add commas to a user input as they type:
$('input.number').keyup(function(event) {
// skip for arrow keys
if(event.which >= 37 && event.which <= 40) return;
// format number
$(this).val(function(index, value) {
return value
.replace(/[^-\d.]/g, "")
.replace(/\B(?=(\d{3})+(?!\d))/g, ",")
;
});
});
This works great, but it does not work for decimals. It adds commas to the decimals, which I don't want.
I could update the code to do a check to see if there are commas after the decimal. However, I think there may be a more elegant solution with Regex.
$('input.number').keyup(function(event) {
// skip for arrow keys
if(event.which >= 37 && event.which <= 40) return;
// format number
$(this).val(function(index, value) {
var num = value
.replace(/[^-\d.]/g, "")
.replace(/\B(?=(\d{3})+(?!\d))/g, ",");
var numSplit = num.split('.');
if(numSplit.length > 1){
num = numSplit[0] + '.' + numSplit[1].replace(/,/g, "");
}
return num;
});
});
I've tried adding a check to first see if a . exists. But I did not write it correctly.
\B(?=[^.](\d{3})+(?!\d))
Is there a better way to do this with regex?
https://codepen.io/anon/pen/gNOgMm
Apply Regex only to the whole number
$('input.number').keyup(function(event) {
// skip for arrow keys
if (event.which >= 37 && event.which <= 40) return;
// format number
$(this).val(function(index, value) {
var num = value
.replace(/[^-\d.]/g, "")
var numSplit = num.split('.');
if (numSplit.length > 1) {
num = numSplit[0]
.replace(/\B(?=(\d{3})+(?!\d))/g, ",") + '.' + numSplit[1].replace(/,/, "");
} else {
num = num.replace(/\B(?=(\d{3})+(?!\d))/g, ",")
}
return num;
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<input class="number">
Shorter Version
$('input.number').keyup(function(event) {
// skip for arrow keys
if (event.which >= 37 && event.which <= 40) return;
// format number
$(this).val(function(index, value) {
var num = value
.replace(/[^-\d.]/g, "")
.replace(/^\.+/g, "")
.replace(/\./, "x").replace(/\./g, "").replace(/x/, ".")
return (/^\d+\.\d+$/.test(num))
? num.replace(/(\d)(?=(\d{3})+(?:\.\d+)$)/g, "$1,")
: num.replace(/\B(?=(\d{3})+(?!\d))/g, ",")
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<input class="number">
So, with a simple replace callback you can match the decimal part
then just return it, or match the assertion for a thousands place
then return ,.
No need to split, it just makes it more complicated.
Since you're using regex, do it all with regex.
The regex expanded:
( \. \d* ) # (1), Decimal part
| # or,
\B # Thousands part
(?=
(?: \d{3} )+
(?! \d )
)
var input = "122341234.188874";
input = input.replace (/[^-\d.]/g, "" );
input = input.replace (/(\.\d*)|\B(?=(?:\d{3})+(?!\d))/g,
function( m, g1 ) // match, group 1
{
if ( g1 > "" )
return g1;
else
return ",";
}
);
console.log(input);
Another thing you may want to consider is to validate the
form after stripping invalid characters.
I believe you could do that with a
replace (/^(?:.*?(-?(?:\d+(?:\.\d*)?|\.\d+))|).*$/g, "$1" );
I want to Check the value to both javascript and php ,which one should be like this format 22.22 or 00.44 or 44 or 55.00.
I have the below code.
$(function(){
// $('.pixcel_rate').keypress(function (event) {
// return isNumber(event, this)
// });
$('.pixcel_rate').keypress(function (event) {
return validateFloatKeyPress($(this).val());
});
});
// THE SCRIPT THAT CHECKS IF THE KEY PRESSED IS A NUMERIC OR DECIMAL VALUE.
function validateFloatKeyPress(evt,el) {
var charCode = (evt.which) ? evt.which : event.keyCode;
var number = el.value.split('.');
if (charCode != 46 && charCode > 31 && (charCode < 48 || charCode > 57)) {
return false;
}
//just one dot (thanks ddlab)
if(number.length>1 && charCode == 46){
return false;
}
//get the carat position
var caratPos = getSelectionStart(el);
var dotPos = el.value.indexOf(".");
console.log(caratPos);
console.log(dotPos);
if( caratPos >1 && dotPos>-1 && (number[0].length > 1)){
return false;
}
if( caratPos > dotPos && dotPos>-1 && (number[1].length > 1)){
return false;
}
return true;
}
function getSelectionStart(o) {
if (o.createTextRange) {
var r = document.selection.createRange().duplicate()
r.moveEnd('character', o.value.length)
if (r.text == '') return o.value.length
return o.value.lastIndexOf(r.text)
} else return o.selectionStart
}
You can use preg_match in php to see if it matches the pattern.
preg_match("/^\d{2}\.\d{2}$|^\d{2}$/", $val);
This matches either two digits, dot, two digits. Or just two digits.
Example test cases:
https://3v4l.org/G6D8l
You can use regex to achieve this. Below is the regex for your requirement.
https://regex101.com/r/N5gbqs/3/
function validateFloatKeyPress(value) {
//returns null if it doesnt match the given regular expression
return value.toString().match(/^(\d{2}|\d{2}\.\d{2})$/)
}
function validateFloatKeyPress(value) {
//returns false if it doesnt match the given regular expression
return (/^(\d{2}|\d{2}\.\d{2})$/).test(value.toString())
}
Hi can someone help me to improve this regular expression on this function to include negative values?
the function is:
function Validate7EntY2Dec(e, field) {
key = e.keyCode ? e.keyCode : e.which
// backspace
if (key == 8) return true
// 0-9 a partir del .decimal
if (field.value != "") {
if ((field.value.indexOf(".")) > 0) {
if (key > 47 && key < 58) {
if (field.value == "") return true
regexp = /[0-9]{2}$/
return !(regexp.test(field.value))
}
}
}
// 0-9
if (key > 47 && key < 58) {
if (field.value == "") return true
regexp = /[0-9]{7}/
return !(regexp.test(field.value))
}
// .
if (key == 46) {
if (field.value == "") return false
regexp = /^[0-9]+$/
return regexp.test(field.value)
}
// other key
return false
}
as far as I get /[0-9]{2}$/ validates two digits after the decimal point, and /[0-9]{7}/ validates seven digist in the integer. I would like to this accept also negative values so the user can insert -1234567.12 for example.
I found this regex ^[+-]?[0-9]{1,9}(?:\.[0-9]{1,2})?$ on other question but dont know how to insert in my function.
Also found that adding a - on /[0-9]{7}/ will accept negative values but it didnt, i did this: /[-0-9]{7}/
I need to keep my function because its been used already.
thank you in advance!
edit:
After the recommendation of #Ian my code was like this:
function Validate7EntY2Dec_Neg(e, field) {
key = e.keyCode ? e.keyCode : e.which
// backspace
if (key == 8) return true
// 0-9 a partir del .decimal
if (field.value != "") {
if ((field.value.indexOf(".")) > 0) {
if (key > 47 && key < 58) {
if (field.value == "") return true
regexp = /[0-9]{2}$/
return !(regexp.test(field.value))
}
}
}
// 0-9
if (key > 47 && key < 58) {
if (field.value == "") return true
regexp = /[0-9]{7}/
return !(regexp.test(field.value))
}
// .
if (key == 46) {
if (field.value == "") return false
regexp = /^[+-]?[0-9]{7}\.[0-9]{2}$/
return regexp.test(field.value)
}
// other key
return false
}
The change is on "function if (key == 46)..."
if (key == 46) {
if (field.value == "") return false
regexp = /^[+-]?[0-9]{7}\.[0-9]{2}$/
return regexp.test(field.value)
}
#Ian how to escape - ??
^[+-]?[0-9]{7}\.[0-9]{2}$ should work. The caret forces start of string and the dollar the end. I have also forced a 7.2 digit number, I assume that is what you want. Also there is the optional +/- to start with.
I propose you stop worrying about keypresses and validate the whole field each time it's changed. I believe this wouldn't cause any performance problem and would vastly improve your code's maintainability.
I would then propose the following code :
function Validate7EntY2Dec_Neg(e, field) {
return /^[+-]?[0-9]{7}\.[0-9]{2}$/.test(field.value);
}
I have placed one text area and I want to put restriction on it ..
Only special characters | should not be allowed to input in text area because I'm using | character in split function.
check this link first
how do i block or restrict special characters from input fields with jquery?
you need to do the opposite here, just look to match for '|'
$('input').bind('keypress', function (event) {
var regex = new RegExp("^[a-zA-Z0-9]+$");
var key = String.fromCharCode(!event.charCode ? event.which : event.charCode);
var patt=/|/g;
var result=patt.test( key ) ;
if (!result) {
event.preventDefault();
return false;
}
});
Call this javascript function at your textbox
function isSpclChar(){
var iChars = "|";
if(document.qfrm.q.value.indexOf(iChars) != -1) {
alert ("This special character is not allowed.");
return false;
}
}
if you don't want to allow special charaters in textbox
then use
var iChars = "!##$%^&*()+=-[]\\\';,./{}|\":<>?";
You can do like this :
Script:
function alpha(e) {
var k = (evt.which) ? evt.which : event.keyCode
return ((k > 64 && k < 91) || (k > 96 && k < 123) || k == 8 || k == 32 || (k >= 48 && k <= 57));
}
HTML :
<input type="text" id="id" onkeypress="return alpha(event);" />
Does anyone know how can I replace the number and symbol (excluding dash and single quote)?
Example:
if I have a string "ABDHN'S-J34H##$";
How can I replace the number and symbol to empty and return me value "ABDHN'S-JH" ?
I have the following code to replay all the char and symbol to empty and only return me number
$(".test").keyup(function (e) {
orgValue = $(".test").val();
if (e.which != 37 && e.which != 39 && e.which != 8 && e.which != 46) {
newValue = orgValue.replace(/[^\d.]/g, "");
$(".test").val(newValue);
}
});
You should allow only letters, dash and single quotes, like this:
newValue = orgValue.replace(/[^a-zA-Z'-]/g, "");
Anything else will be replaced by "".
You can use this regex:
string.replace(/^[a-zA-Z'-]+$/, '')
The caret ^ inside a character class [] will negate the match. This regex will convert all characters other than a-z, A-Z, single quote and hyphen to empty
You could replace symbols by skipping them through keycode value on the keyboard.
Link for keycode values for reglar keyboard:
http://www.w3.org/2002/09/tests/keys.html
$("#your control").bind("keydown keyup", doItPlease);
function doItPlease(e)
{
// First 2 Ifs are for numbers for num pad and alpha pad numbers
if (e.which < 106 && e.which > 95)
{
return false; // replace your values or return false
}
else if (e.which < 58 && e.which > 47)
{
// replace your values or return false
} else {
var mycharacters = [8, 9, 33, 34, 35 // get your coders from above link];
for (var i = 0; i < mycharacters.length; i++) {
if (e.which == mycharacters[i]) {
// replace your characters or just
// return false; will cancel the key down and wont even allow it
}
e.preventDefault();
}
"ABDHN'S-J34H##$".replace(/[^\-'\w]/g, '')
"ABDHN'S-J34H##$".replace(/[0-9]|[\'##$]/g, "");