Regular expression for upper case letter only in JavaScript - 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/

Related

Regex - Output character not valid

I'm trying to create a function to check if a field is valid based on a set of characters and, if not, output which ones are not allowed. Don't know if it is the best approach, but basically instead of telling the user which ones he can use, I want to tell which ones he can't.
function allowedString(field){
var validCharacters = new RegExp('^[a-zA-Z0-9áéíóúÁÉÍÓÚñÑ_-¿?¡!.,;:$() ]*$');
if(!validCharacters.test(field.val())){
var invalid = ?;
return "Invalid characters: "+invalid;
}
}
Using your character set in your regex, you can remove all those characters from the string and resultant will be the non-allowed characters. Try this JS codes,
function allowedString(s){
var validCharacters = new RegExp('^[a-zA-Z0-9áéíóúÁÉÍÓÚñÑ_-¿?¡!.,;:$() ]*$');
if(!validCharacters.test(s)){
var invalid = s.replace(/[a-zA-Z0-9áéíóúÁÉÍÓÚñÑ_-¿?¡!.,;:$() ]*/g,'');
return "Invalid characters: "+invalid;
} else {
return "All characters are valid"; // return any message you want
}
}
console.log(allowedString('aa##bb##'));
console.log(allowedString('abc'));
console.log(allowedString('aa##bb##~~^^'));
And change your field parameter in function back to your original code.
You can split the string and deal with it as with an array (not sure about the performance, though).
function allowedString(field){
const validCharacters = new RegExp('^[a-zA-Z0-9áéíóúÁÉÍÓÚñÑ_-¿?¡!.,;:$() ]*$');
const disallowed = field.val().split('').filter(x => !validCharacters.test(x));
if (disallowed.length) {
return disallowed.join('');
}
}
I'd reverse the test: Is there an invalid character within the string?
Take care you have to escape the dash in a character class except in first and last position.
function allowedString(field){
var invalidCharacters =/([^a-zA-Z0-9áéíóúÁÉÍÓÚñÑ_\-¿?¡!.,;:$() ])/;
invalid = invalidCharacters.exec(field);
if (invalid != null) {
return "Invalid characters: "+invalid[1];
} else {
return "OK";
}
}
console.log(allowedString('abc'));
console.log(allowedString('abc#def'));
console.log(allowedString('abc§def'));

Javascript RegEx Syntax Snafu

I have a string. I want to allow for upper case letters, lower case letters, numbers, and these special characters: !$/%##.
I would expect this to pass: abcABC123!
I would expect this to fail: abcABC123*
I have tried the following code:
var myString = 'abcABC123*'
// var myString = 'abcABC123!'
if (myString.match(/^[a-zA-Z0-9]!\$\/%##/)) {
alert('this works!');
} else {
alert('Invalid Character');
}
As the code sits now, I always hit the else statement. Be gentle I am not a RegEx expert, or an expert of any kind for that matter.
Note: I would appreciate a pure JavaScript Solution.
Check the snippet, change the regEx pattern to ^[a-zA-Z0-9!%##]+$/g so this could easily work
var myString = 'abcABC123%'
// var myString = 'abcABC123!'
if (myString.match(/^[a-zA-Z0-9!\%\$##]+$/g )) {
alert('this works!');
} else {
alert('Invalid Character in your password');
}
Add those characters to the character set and use $ for asserting position at end of string:
^[A-Za-z0-9!$/%##]+$
Check the regex here.
Snippet:
var myString = 'abcABC123!'
if (myString.match(/^[A-Za-z0-9!$/%##]+$/)) {
console.log('this works!');
} else {
console.log('Invalid Character');
}
Check a live JavaScript fiddle here.

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');
}
}

Writing a regex expression for special characters in 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
}

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 ... )

Categories

Resources