I am trying to implement "alpha" validation on Arabic alphabet characters input, using the JavaScript regex /[\u0600-\u06FF]/ as instructed in this post. I want to accept only Arabic alphabet characters and spaces.
Now the problem is it gives the following result:
r = /[\u0600-\u06FF]/
r.test("abcd") // false - correct
r.test("##$%^") // false - correct
r.test("س") // true - correct
r.test("abcd$$#5س") // true - should be false
r.test("abcdس") // true - should be false
If a single matching character is given, then it is classifying the whole input as acceptable, even if the rest of the input is full of unacceptable chars. What regex should I be using instead?
You need to add ^ and $ anchors to the regular expression, as well as a + to allow multiple characters.
Try this:
/^[\u0600-\u06FF]+$/
I'm not sure if "Arabic spaces" that you mentioned are included in the character range there, but if you want to allow white space in the string then just add a \s inside the [] brackets.
You can explicitly allow some keys e-g: numpad, backspace and space, please check the code snippet below:
function restrictInputOtherThanArabic($field)
{
// Arabic characters fall in the Unicode range 0600 - 06FF
var arabicCharUnicodeRange = /[\u0600-\u06FF]/;
$field.bind("keypress", function(event)
{
var key = event.which;
// 0 = numpad
// 8 = backspace
// 32 = space
if (key==8 || key==0 || key === 32)
{
return true;
}
var str = String.fromCharCode(key);
if ( arabicCharUnicodeRange.test(str) )
{
return true;
}
return false;
});
}
// call this function on a field
restrictInputOtherThanArabic($('#firstnameAr'));
Related
I'm trying to use a regular expression to validate the input on a textbox
The expression should allow only numbers, maxmium two decimals, max one comma (,) and one minus symbol in front of the number (optional).
Valid:
0,25
10,2
-7000
-175,33
15555555555555,99
invalid:
9,999
15.03
77,77,77
etc
I'm using ^[-+]?[\d ]+(,\d{0,2})?$
The regex is used in a Jquery code to prevent the user from entering invalid numbers (event.preventDefault()):
$("input[name*='TB_mytbx']").on('keypress', function (event) {
var regex = new RegExp("^[-+]?[\d ]+(,\d{0,2})?$", "g");
var key = String.fromCharCode(!event.charCode ? event.which : event.charCode);
if (!regex.test(key)) {
event.preventDefault();
return false;
}
});
Only a part of the regular expression seems to work.
It works with numbers (It does not allow me to enter letters) but it also won't allow commas (,) and the minus (-).
What am I doing wrong?
Edit
Before I used:
if (focused.val().indexOf(',') != -1) {
var number = (focused.val().split(','));
if (number[1] && number[1].length >= 2) {
event.preventDefault();
return;
}
But this gives annoying behavior. As soon as you enter a number with two digits you can't make edits anymore. For example: you can't change 200,50 to 300,50 or 100 300,50. (You get the point). I hoped that a regex could change that somehow.
I think you're massively over-complicating the regex. This should be plenty:
^-?\d+(,\d\d)?$
^ Start of line,
-? Optional minus sign,
\d+ Followed by a bunch of digits,
(,\d\d)? Followed by a comma and 2 digits, which are all 3 optional.
(alternative: (,\d{2})?)
$ End of line.
var regex = /^-?\d+(,\d\d)?$/;
console.log(regex.test('0,25'));
console.log(regex.test('-175,33'));
console.log(regex.test('15555555555555,99'));
console.log(regex.test('9,999'));
console.log(regex.test('15.03'));
console.log(regex.test('77,77,77'));
There you have a regex to validate the input value.
Now, that block of code can be replaced with this:
$("input[name*='TB_mytbx']").on('keypress', function (event) {
var regex = /^-?\d+(,\d\d)?$/;
var value = $(this).val(); // Use the field's value, instead of the pressed key.
if (!regex.test(value)) {
event.preventDefault();
return false;
}
});
For those of you who wanna know, I solved it using this code
$("input[name*='mythingy']").on('keypress', function (event) {
var theEvent = event || window.event;
var key = theEvent.keyCode || theEvent.which;
key = String.fromCharCode(key);
var value = this.value;
var value = value.replace(value.substring(theEvent.currentTarget.selectionStart, theEvent.currentTarget.selectionEnd), "");
value = [value.slice(0, theEvent.currentTarget.selectionStart), key, value.slice(theEvent.currentTarget.selectionStart)].join('');
var regex = /^[-+]?([\d ]+(,\d{0,2})?)?$/;
if (!regex.test(value)) {
theEvent.returnValue = false;
if (theEvent.preventDefault) theEvent.preventDefault();
}
});
I am trying to make a HTML form that accepts a rating through an input field from the user. The rating is to be a number from 0-10, and I want it to allow up to two decimal places. I am trying to use regular expression, with the following
function isRatingGood()
{
var rating = document.getElementById("rating").value;
var ratingpattern = new RegExp("^[0-9](\.[0-9][0-9]?)?$");
if(ratingpattern.test(rating))
{
alert("Rating Successfully Inputted");
return true;
}
else
{
return rating === "10" || rating === "10.0" || rating === "10.00";
}
}
However, when I enter any 4 or 3 digit number into the field, it still works. It outputs the alert, so I know it is the regular expression that is failing. 5 digit numbers do not work. I used this previous answer as a basis, but it is not working properly for me.
My current understanding is that the beginning of the expression should be a digit, then optionally, a decimal place followed by 1 or 2 digits should be accepted.
You are using a string literal to created the regex. Inside a string literal, \ is the escape character. The string literal
"^[0-9](\.[0-9][0-9]?)?$"
produces the value (and regex):
^[0-9](.[0-9][0-9]?)?$
(you can verify that by entering the string literal in your browser's console)
\. is not valid escape sequence in a string literal, hence the backslash is ignored. Here is similar example:
> "foo\:bar"
"foo:bar"
So you can see above, the . is not escaped in the regex, hence it keeps its special meaning and matches any character. Either escape the backslash in the string literal to create a literal \:
> "^[0-9](\\.[0-9][0-9]?)?$"
"^[0-9](\.[0-9][0-9]?)?$"
or use a regex literal:
/^[0-9](\.[0-9][0-9]?)?$/
The regular expression you're using will parsed to
/^[0-9](.[0-9][0-9]?)?$/
Here . will match any character except newline.
To make it match the . literal, you need to add an extra \ for escaping the \.
var ratingpattern = new RegExp("^[0-9](\\.[0-9][0-9]?)?$");
Or, you can simply use
var ratingPattern = /^[0-9](\.[0-9][0-9]?)?$/;
You can also use \d instead of the class [0-9].
var ratingPattern = /^\d(\.\d{1,2})?$/;
Demo
var ratingpattern = new RegExp("^[0-9](\\.[0-9][0-9]?)?$");
function isRatingGood() {
var rating = document.getElementById("rating").value;
if (ratingpattern.test(rating)) {
alert("Rating Successfully Inputted");
return true;
} else {
return rating === "10" || rating === "10.0" || rating === "10.00";
}
}
<input type="text" id="rating" />
<button onclick="isRatingGood()">Check</button>
Below find a regex candidate for your task:
^[0-1]?\d(\.\d{0,2})?$
Demo with explanation
var list = ['03.003', '05.05', '9.01', '10', '10.05', '100', '1', '2.', '2.12'];
var regex = /^[0-1]?\d(\.\d{0,2})?$/;
for (var index in list) {
var str = list[index];
var match = regex.test(str);
console.log(str + ' : ' + match);
}
This should also do the job. You don't need to escape dots from inside the square brackets:
^((10|\d{1})|\d{1}[.]\d{1,2})$
Also if you want have max rating 10 use
10| ---- accept 10
\d{1})| ---- accept whole numbers from 0-9 replace \d with [1-9]{1} if don't want 0 in this
\d{1}[.]\d{1,2} ---- accept number with two or one numbers after the coma from 0 to 9
LIVE DEMO: https://regex101.com/r/hY5tG4/7
Any character except ^-]\ All characters except the listed special characters are literal characters that add themselves to the character class. [abc] matches a, b or c literal characters
Just answered this myself.
Need to add square brackets to the decimal point, so the regular expression looks like
var ratingpattern = new RegExp("^[0-9]([\.][0-9][0-9]?)?$");
How can I remove everything but numbers,letters and hyphens from a string with jQuery?
I found this code which allows only alphanumerical characters only but I'm not sure how I would go about adding a hyphen.
$('#text').keypress(function (e) {
var regex = new RegExp("^[a-zA-Z0-9]+$");
var str = String.fromCharCode(!e.charCode ? e.which : e.charCode);
if (regex.test(str)) {
return true;
}
e.preventDefault();
return false;
});
You just have to change the regexp to this : "^[a-zA-Z0-9\-]+$".
Note that the hyphen is escaped using \, otherwise it is used to specify a range like a-z (characters from a to z).
This code will only check if the last typed character is in the allowed list, you might also want to check if after a paste in your field, the value is still correct :
// The function you currently have
$('#text').keypress(function (e) {
var allowedChars = new RegExp("^[a-zA-Z0-9\-]+$");
var str = String.fromCharCode(!e.charCode ? e.which : e.charCode);
if (allowedChars.test(str)) {
return true;
}
e.preventDefault();
return false;
}).keyup(function() {
// the addition, which whill check the value after a keyup (triggered by Ctrl+V)
// We take the same regex as for allowedChars, but we add ^ after the first bracket : it means "all character BUT these"
var forbiddenChars = new RegExp("[^a-zA-Z0-9\-]", 'g');
if (forbiddenChars.test($(this).val())) {
$(this).val($(this).val().replace(forbiddenChars, ''));
}
});
Since there is so much attention on including a hyphen within a character class amongst these answers and since I couldn't find this information readily by Googling, I thought I'd add that the hyphen doesn't need to be escaped if it's the first character in the class specification. As a result, the following character class will work as well to specify the hyphen in addition to the other characters:
[-a-zA-Z0-9]
I think you can just put a hyphen inside the square brackets.
"^[a-z A-Z 0-9 -]+$"
I am having a problem to get the simple reges for alphanumeric chars only work in javascript :
var validateCustomArea = function () {
cString = customArea.val();
var patt=/[0-9a-zA-Z]/;
if(patt.test(cString)){
console.log("valid");
}else{
console.log("invalid");
}
}
I am checking the text field value after keyup events from jquery but the results are not expected, I only want alphanumeric charachters to be in the string
This regex:
/[0-9a-zA-Z]/
will match any string that contains at least one alphanumeric character. I think you're looking for this:
/^[0-9a-zA-Z]+$/
/^[0-9a-zA-Z]*$/ /* If you want to allow "empty" through */
Or possibly this:
var string = $.trim(customArea.val());
var patt = /[^0-9a-z]/i;
if(patt.test(string))
console.log('invalid');
else
console.log('valid');
Your function only checks one character (/[0-9a-zA-Z]/ means one character within any of the ranges 0-9, a-z, or A-Z), but reads in the whole input field text. You would need to either loop this or check all characters in the string by saying something like /^[0-9a-zA-Z]*$/. I suggest the latter.
I fixed it this way
var validateCustomArea = function () {
cString = customArea.val();
console.log(cString)
var patt=/[^0-9a-zA-Z]/
if(!cString.match(patt)){
console.log("valid");
}else{
console.log("invalid");
}
}
I needed to negate the regex
Javascript regex to validate that it contains 6 characters and in which one character (1) should be a number.
var pwdregex =/^[A-Za-z1-9]{6}$/;
This will guarantee exactly one number (i.e. a non-zero decimal digit):
var pwdregex = /^(?=.{6}$)[A-Za-z]*[1-9][A-Za-z]*$/;
And this will guarantee one or more consecutive number:
var pwdregex = /^(?=.{6}$)[A-Za-z]*[1-9]+[A-Za-z]*$/;
And this will guarantee one or more not-necessarily-consecutive number:
var pwdregex = /^(?=.{6}$)[A-Za-z]*(?:[1-9][A-Za-z]*)+$/;
All of the above expressions require exactly six characters total. If the requirement is six or more characters, change the {6} to {6,} (or remove the $ from {6}$).
All possible combinations of 1 digit and alphanumeric chars with a length of 6.
if (subject.match(/^[a-z]{0,5}\d[a-z]{0,5}$/i) && subject.length == 6) {
// Successful match
} else {
// Match attempt failed
}
[Edit] Fixed obvious bug...
If you are ok with using a function instead of a regex you can do this:
var sixAlphaOneDigit = function(s) {
return !!((s.length==6) && s.replace(/\d/,'').match(/^[A-Za-z]{5}$/));
};
sixAlphaOneDigit('1ABCDE'); // => true
sixAlphaOneDigit('ABC1DE'); // => true
sixAlphaOneDigit('ABCDE1'); // => true
sixAlphaOneDigit('ABCDE'); // => false
sixAlphaOneDigit('ABCDEF'); // => false
sixAlphaOneDigit('ABCDEFG'); // => false
If you want to do it strictly in a regex then you could build a terribly long pattern which enumerates all possibilities of the position of the digit and the surrounding (or leading, or following) characters.