Regex - Output character not valid - javascript

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

Related

Javascript remove all characters by regex rules

Who can help me with the following
I create a rule with regex and I want remove all characters from the string if they not allowed.
I tried something by myself but I get not the result that I want
document.getElementById('item_price').onkeydown = function() {
var regex = /^(\d+[,]+\d{2})$/;
if (regex.test(this.value) == false ) {
this.value = this.value.replace(regex, "");
}
}
The characters that allowed are numbers and one komma.
Remove all letters, special characters and double kommas.
If the user types k12.40 the code must replace this string to 1240
Who can help me to the right direction?
This completely removes double occurrences of commas using regex, but keeps single ones.
// This should end up as 1,23243,09
let test = 'k1,23.2,,43d,0.9';
let replaced = test.replace(/([^(\d|,)]|,{2})/g, '')
console.log(replaced);
I don't believe there's an easy way to have a single Regex behave like you want. You can use a function to determine what to replace each character with, though:
// This should end up as 1232,4309 - allows one comma and any digits
let test = 'k12,3.2,,43,d0.9';
let foundComma = false;
let replaced = test.replace(/(,,)|[^\d]/g, function (item) {
if (item === ',' && !foundComma) {
foundComma = true;
return ',';
} else {
return '';
}
})
console.log(replaced);
This will loop through each non-digit. If its the first time a comma has appeared in this string, it will leave it. Otherwise, if it must be either another comma or a non-digit, and it will be replaced. It will also replace any double commas with nothing, even if it is the first set of commas - if you want it to be replaced with a single comma, you can remove the (,,) from the regex.

Regex requirement to have # symbol only once in a string

I am new to javaScript and the problem I am facing is that I have to match the # symbol and make sure it is allowed only once in a string. To do so I have written the following regex.
var regexpat=/[#]{1}/;
if(regexpat.test(valu))
testresults = true;
else
{
alert("Please input a valid email address!");
testresults = false;
}
My regex is working for the following input value: abcd#abc#abc.com. However, if I provide the input value as "abcd#"#abc.com it is not throwing the alert error message.
How can I change my regex so that it will work for "abcd#"#abc.com?
Your regexp just tests whether there's a single # in the string, it doesn't reject more than one. Use:
var regexppat = /^[^#]+#[^#]+$/;
This matches an # that's surrounded by characters that aren't #.
var valu;
var regexpat = /^[^#]+#[^#]+$/;
while (valu = prompt("Enter email")) {
if (regexpat.test(valu))
console.log(valu + " is valid");
else {
console.log(valu + " is invalid");
}
}
The easy way could also be to use the split("#") for this:
var value = 'abcd##';
if(value.split("#").length === 2){
testresults = true;
}else{
alert("Please input a valid email address!");
testresults = false;
}
Just split your string with # and since you require only one occurrence of # there must be an array of length 2 so you can compare the array with length 2. If the array length is greater than 2 then there are more than one occurrence of #
E-Mail regex is much more, than just the occurence of just one # character. This is the email-regex specified in the W3C Spec (e.g. used for <input type="email">):
/^[a-zA-Z0-9.!#$%&’*+/=?^_`{|}~-]+#[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/

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

Javascript regex doesn't give error message when it should

I try to input the following value "f+11111111111", and my code doesn't display error message. I tried to remove regex2 condition, and then it worked. But how come? It's an AND condition, why does it act like it's an OR operator?
function validatePhone()
{
var phone = document.getElementById("phone").value;
var regex1 =/^[\+\d][\s(\-\d][\s()\-\d]{8,}/g;
var regex2 = /\D*(\d\D*){11}/g;
if (!phone.match(regex1) && !phone.match(regex2)) {
producePrompt("Error", "comment_phone_prompt");
return false;
}
}
function producePrompt(message, promptLocation)
{
document.getElementById(promptLocation).innerHTML = message;
}
Your second regular expression /\D*(\d\D*){11}/g matches the given string f+11111111111 and therefore the whole condition evaluates to false. You can visualise your regular expressions using regexper.com.
I'm not sure what you're trying to do but mind that even this string is matched by the second regex: 'f+1dsadsadasda123131231dsdadai-094i-)#)#(#)_(#_!' Is this what you want?
Second regex matches everything. Single regex is enough.
function validatePhone() {
var phone = document.getElementById("phone").value;
var regex1 = /^(\+\d)?(\(|-)?\d{3}(\)|-)?\d{3}-?\d{4}$/;
//match +1-800-123-45678, (555)123-4567, and so on
if (!regex1.test(phone)){
producePrompt("Error", "comment_phone_prompt");
return false;
}
return true;//both sides should return
}

javascript code to check special characters

I have JavaScript code to check if special characters are in a string. The code works fine in Firefox, but not in Chrome. In Chrome, even if the string does not contain special characters, it says it contains special characters.
var iChars = "~`!#$%^&*+=-[]\\\';,/{}|\":<>?";
for (var i = 0; i < chkfile.value.length; i++)
{
if (iChars.indexOf(chkfile.value.charAt(i)) != -1)
{
alert ("File name has special characters ~`!#$%^&*+=-[]\\\';,/{}|\":<>? \nThese are not allowed\n");
return false;
}
}
Suppose I want to upload a file desktop.zip from any Linux/Windows machine.
The value of chkfile.value is desktop.zip in Firefox, but in Chrome the value of chkfile.value is c://fakepath/desktop.zip. How do I get rid of c://fakepath/ from chkfile.value?
You can test a string using this regular expression:
function isValid(str){
return !/[~`!#$%\^&*+=\-\[\]\\';,/{}|\\":<>\?]/g.test(str);
}
Try This one.
function containsSpecialCharacters(str){
var regex = /[ !##$%^&*()_+\-=\[\]{};':"\\|,.<>\/?]/g;
return regex.test(str);
}
Directly from the w3schools website:
var str = "The best things in life are free";
var patt = new RegExp("e");
var res = patt.test(str);
To combine their example with a regular expression, you could do the following:
function checkUserName() {
var username = document.getElementsByName("username").value;
var pattern = new RegExp(/[~`!#$%\^&*+=\-\[\]\\';,/{}|\\":<>\?]/); //unacceptable chars
if (pattern.test(username)) {
alert("Please only use standard alphanumerics");
return false;
}
return true; //good user input
}
Did you write return true somewhere? You should have written it, otherwise function returns nothing and program may think that it's false, too.
function isValid(str) {
var iChars = "~`!#$%^&*+=-[]\\\';,/{}|\":<>?";
for (var i = 0; i < str.length; i++) {
if (iChars.indexOf(str.charAt(i)) != -1) {
alert ("File name has special characters ~`!#$%^&*+=-[]\\\';,/{}|\":<>? \nThese are not allowed\n");
return false;
}
}
return true;
}
I tried this in my chrome console and it worked well.
You could also do it this way.
specialRegex = /[^A-Z a-z0-9]/
specialRegex.test('test!') // evaluates to true
Because if its not a capital letter, lowercase letter, number, or space, it could only be a special character
If you don't want to include any special character, then try this much simple way for checking special characters using RegExp \W Metacharacter.
var iChars = "~`!#$%^&*+=-[]\\\';,/{}|\":<>?";
if(!(iChars.match(/\W/g)) == "") {
alert ("File name has special characters ~`!#$%^&*+=-[]\\\';,/{}|\":<>? \nThese are not allowed\n");
return false;
}

Categories

Resources