Quantcast
Channel: Adobe Community : Popular Discussions - JavaScript
Viewing all articles
Browse latest Browse all 12130

CharAt in a keystroke event using regular expression

$
0
0

I'm working on a canadian postal code field.  I'm using a regular expression to validate the value.

 

//accepts "A9A 9A9", "A9A9A9" or "" as valid entries excluding letters D, F, I, O, Q, U and W as well as Z as the first digit.

var re = /^[ABCEGHJKLMNPRSTVXY]\d[ABCEGHJKLMNPRSTVWXYZ]( )?\d[ABCEGHJKLMNPRSTVWXYZ]\d$|^$/i;

if(re.test(event.value) == false){
app.alert("Code postal invalide", 0, 0,"CODE POSTAL");
event.value = "";
}

 

I also added a keystroke event to prescan every digit and toUpperCase() them.

 

//accepts letters, numbers, backspace or spaces

var re = /[ABCEGHJKLMNPRSTVWXYZ]|\d|^$|\s/i;

if (!event.willCommit){
if(re.test(event.change) == false){
  event.rc = false;
}
else{
  event.change = event.change.toUpperCase();
}
}

 

I want to Replicate the behavior of an arbitrary mask where I can force a character to appear at a specific position.  In this example, instead of letting the user decide wether he adds a "space" or not between the two parts of the code, I want to:

1-Remove "\s" in the keystroke regexp so the user cannot use "space";

2-Replace "( )?" for "( )" in the validation regexp;

3-Force a space at charAt(3).

 

Is it possible to have it appear while the user is still typing or is my only option to change the value once committed or as a cutom format script?

In the same manner, is it possible to specify a different regexp keystroke depending on the position of each character?

 

charAt(0), charAt(2), charAt(5) would be letters

charAt(1), charAt(6), charAt(7), would be numbers

charAt(3), would automatically add a "space"

in the end, I want the same behavior as an arbitrary mask without the annoying alert when entering a wrong digit.


Viewing all articles
Browse latest Browse all 12130

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>