Writing a regex expression for special characters in JavaScript - javascript

I know my code is wrong, I am trying to test for certain characters, and as long as they exist for each char in the input field, it will pass true, otherwise pass false.
function isChar(value) {
//Trying to create a regex that allows only Letters, Numbers, and the following special characters # . - ( ) # _
if (!value.toString().match(/#.-()#_$/)) {
return false;
} return true;
}

Assuming you're actually passing a character (you don't show how this is called), this should work:
function isChar(value) {
if (!value.toString().match(/[a-z0-9#.\-()#_\$]/i)) {
return false;
} else
return true;
}
console.log(isChar('%')); // false
console.log(isChar('$')); // true
console.log(isChar('a')); // true
If instead you're passing a string, and wanting to know if all the characters in the string are in this "special" list, you'll want this:
function isChar(value) {
if (! value.match(/^[a-z0-9#.\-()#_\$]*$/i)) {
return false;
} else
return true;
}
console.log(isChar("%$_")); // false
console.log(isChar("a$_")); // true

Characters that have meaning in regexp need to be escaped with \. So for example you would replace $ with \$ and so on for the other such characters. So the final regexp would look like:
#.\-()#_\$
Since you need to escape both the - and the $.

The \w class will catch the alpha numeric. The rest you provided (but properly escaped):
function isChar(value) {
return value.toString().match(/[\w#.\-()#_\$]/) ? true : false
}

Related

Regex which should not allow any special characters except ,

I am trying to create a regular expression which does not allow any special characters except ,, . and they should not come side by side.
For example: STax.sdn,skm should be accepted whereas SDs,.Hnj should throw an error message. I have used the below code, however it is accepting , and . side by side which I don't want.
function validateAnnouncementTags(){
var announcementTags = document.getElementById("announcementTags").value;
if (announcementTags.search(/[<>'+\"\/`\\\[\]^={}%;##!$&*()?:|]/)>-1 ) {
$('#announcementTagsSpecialCharError').addClass('show');
} else {
$('#announcementTagsSpecialCharError').addClass('hide');
$('#announcementTagsSpecialCharError').removeClass('show');
}
}
use this pattern:
/^(?!.*[\.,])/
Based on your comments, I am assuming that you want to accept any letters separated by periods or commas. How about we:
Check for valid characters, and
Ensure that no "special" chars occur adjacent?
we can use
function validateAnnouncementTags() {
var announcementTags=document.getElementById("announcementTags").value;
if (announcementTags.match(/[a-zA-Z\.,]*/)[0] != annoucementTags
|| announcementTags.search(/[\.,][\.,]/) >= 0
) {
$('#announcementTagsSpecialCharError').addClass('show');
} else {
$('#announcementTagsSpecialCharError').addClass('hide');
$('#announcementTagsSpecialCharError').removeClass('show');
}
}
But, if I may be so bold as to assume more structure to your acceptable syntax:
Accept any sequence of letters separated by a comma or period
The sequence will not start with a comma or period
The sequence can end with a comma or period
Then we can use:
function validateAnnouncementTags() {
var announcementTags=document.getElementById("announcementTags").value;
if (announcementTags.match(/([a-z0-9]+[\.,]?)*/)[0] != annoucementTags ) {
$('#announcementTagsSpecialCharError').addClass('show');
} else {
$('#announcementTagsSpecialCharError').addClass('hide');
$('#announcementTagsSpecialCharError').removeClass('show');
}
}

validation function doesn't work

I have created a java script function, it should validate the input character that should contain 10 characters and can contain alphanumeric characters, but this function does not work, please help me
function ValidateNIC(id)
{
var letters = /^[0-9a-zA-Z ]+$/;
while(id.value.length==10)
if(id.value.match(letters))
{
return true;
}
else
{
alert('NIC must have alphanumeric characters only or should contain 10 charaters');
id.focus();
return false;
}
}
With your code as it stands, if the length is not 10, then nothing else happens. A better approach might be:
if ((id.value.length == 10) && id.value.match(letters)) {
return true;
}
alert("NIC must ...");
id.focus();
return false;
You can put all the conditions for validation in Regex like ^[a-zA-Z0-9]{10}$. Note that additional {10} in the regex pattern string for creating a match only when the length is 10 exactly.
Then you can make use of the Regex Object test method, which test the regex pattern against a string and returns true if the match is successful and false otherwise.
Complete modified snippet below with positive and negative test cases.
function ValidateNIC(id){
var aphaPattern10 = /^[a-zA-Z0-9]{10}$/g;
var result = aphaPattern10.test(id.value);
if(!result){
alert('NIC must have alphanumeric characters only or should contain 10 charaters');
//id.focus();
}
return result;
}
var testObjPass = { value : "012345678a"}
console.log(ValidateNIC(testObjPass));
var testObjFail = { value : "012345678a21312"}
console.log(ValidateNIC(testObjFail));
The following code checks the following
NIC must have alphanumeric characters only or should contain 10 charaters.
So if it is only 10 characters then it will not alert else, it will test the regex. Considering id is an object with key value
function ValidateNIC(id)
{
var letters = /^[0-9a-zA-Z ]+$/;
if(id.value.length!==10){
if(id.value.match(letters))
{
return true;
}
else
{
alert('NIC must have alphanumeric characters only or should contain 10 charaters');
id.focus();
return false;
}
}
}

How to filter Chinese characters with regular expression in javascript

I need a regular expression to test a string.
The string can only contain English letters, number, hyphen and underscore.
previously I have one to test a string whether it only contains positive numbers(zero included); I used:
if(!/^\d+$/.test(number)) {
alert('..bla');
} else {
return true;
};
So I want a similar one. I have read:
Regular expressions and Chinese;
and Regex Letters, Numbers, Dashes, and Underscores;
But these two does not seem to fix my problem.
!/[a-zA-Z0-9\-\_]+$/.test('_-bla') // return false
!/[a-zA-Z0-9\-\_]+$/.test('_-bl我a') // return false
!/[a-zA-Z0-9\-\_]+$/.test('_-bl我') // return true
!/[a-zA-Z0-9\-\_]+/.test('_-bl我') // return false
!/[a-zA-Z0-9\-\_]+/.test('_-bl我a') // return false
Thanks in advance. :)
Use ^[-\w]+$. \w matches digits, alphabets, _.
/^[-\w]+$/.test('_-bla') // true
/^[-\w]+$/.test('_-bl我a') // false
/^[-\w]+$/.test('_-bl我') // false
/^[-\w]+$/.test('_-bl我') // false
/^[-\w]+$/.test('_-bl我a') // false
I assume you're looking for this output. Add the caret (^) which means start of string and ($) meaning end of string to your regular expressions.
/^[a-zA-Z0-9_-]+$/.test('_-bla'); // True
/^[a-zA-Z0-9_-]+$/.test('_-bl我a'); // False
/^[a-zA-Z0-9_-]+$/.test('_-bl我'); // False
/^[a-zA-Z0-9_-]+$/.test('_-bl我'); // False
/^[a-zA-Z0-9_-]+$/.test('_-bl我a'); // False
You can just use \w instead which matches word characters (a-z, A-Z, 0-9, _)
/^[\w-]+$/

javascript regex does not work for sentence string

I am writing a function which takes string as an argument. Then if the string begins with capital letter then return true otherwise return false. But my current function only works for one word string which I want it to work for both one word and a whole sentence. How can I improve my code to achieve this? Secondly, it should not work when numbers are passed inside sentence. How can I do this?
Here is my code
function takeString (str) {
var regex = /^[A-Za-z]+$/;
if (str.match(regex)) {
if (str.charAt(0) === str.toUpperCase().charAt(0)) {
alert('true');
return true;
} else {
alert('false');
return false;
}
} else {
alert('Only letters please.');
}
}
takeString('This is'); // shows Only letters please which is wrong. this should work
takeString('String); // returns true which right
takeString('string'); // returns false which is right
takeString('This is 12312321'); // shows only letters please which is right bcoz it has digits
takeString('12312312'); // show Only letters please which is right.
​
Spaces aren't letters. You have to add them into your character set:
> 'This is a string'.match(/^[A-Za-z]+$/);
null
> 'This is a string'.match(/^[A-Za-z\s]+$/);
["This is a string"]
\s matches all whitespace, so if you don't want to match tabs, replace \s with a space.
Here's a slightly more condensed version of your code:
function takeString(str) {
return str.match(/^[A-Z][A-Za-z ]*$/);
}
along with the regex advice given by Blender, you'll want to also do the following (in order to satisfy the need to check each word ... assuming words are space or tab separated only:
use the split function to break the string into words ( var mywords = str.split(/\s+/) )
iterate over mywords array returned by split, checking each array element against the regex
return an error if the regex doesnt match
return success if you match every word
takeString (str) {
var mywords = str.split(/\s+/);
for (i = 0; i < mywords.length; i++) {
if (str.match(/^[A-Z][A-Za-z]*$/) != true) {
return false;
}
}
return true;
}
(someone needs to check my js ... )

Regular expression for upper case letter only in JavaScript

How can I validate a field only with upper case letters which are alphabetic. So, I want to match any word made of A-Z characters only.
Try something like this for the javascript validation:
if (value.match(/^[A-Z]*$/)) {
// matches
} else {
// doesn't match
}
And for validation on the server side in php:
if (preg_match("/^[A-Z]*$/", $value)) {
// matches
} else {
// doesn't match
}
It's always a good idea to do an additional server side check, since javascript checks can be easily bypassed.
var str = 'ALPHA';
if(/^[A-Z]*$/.test(str))
alert('Passed');
else
alert('Failed');
Try this:
if (<value>.match(/^[A-Z]*$/)) {
// action if is all uppercase (no lower case and number)
} else {
// else
}
here is a fiddle: http://jsfiddle.net/WWhLD/

Categories

Resources