Home > OS >  Variable validation according to javascript rules using RegEx
Variable validation according to javascript rules using RegEx

Time:07-25

Is there any ways of improving this code?

I want variables that doesn't start with numbers and doesn't include special characters, such as (!@#$%^) When I join these RegEx patterns it does not work properly when variable includes special characters

            let text = prompt('add variable name');
            let pattern = /^[^0-9]/g;                    // check if it starts with number
            let condition = pattern.test(text);

            if (condition == true) {
                pattern = /[^a-zA-Z0-9$_]/;                //check if it contains special characters (!@#$%^*) except ($ , _)
                condition = pattern.test(text);
                if (condition == false) {
                    console.log("Variable name is Valid");
                }
                else {
                    console.log('Variable name Is Not Valid');  //includes special character
                }
            }
            else {
                console.log('Variable name Is Not Valid'); //starts with number
            }

CodePudding user response:

Using condition is already a boolean, so you can use if (condition)

You might rewrite your code using a pattern that checks that the string does not start with a digit, and in the character class specify all allowed characters and match until the end of the string $

In this case you can shorten the ranges to word characters \w and the dollar sign $

let text = prompt('add variable name');
let pattern = /^(?!\d)[\w$] $/;
let condition = pattern.test(text);

if (condition) {
  console.log("Variable name is Valid");
} else {
  console.log('Variable name Is Not Valid');
}

  • Related