/    Sign up×
Community /Pin to ProfileBookmark

A regular expression question

All,

I have a regular expression (below) and I’m walking through a entire web form (say there are 10 elements). I only want to print the alert message if the form name matches one of the three below(REQUIRED_<something). But, my problem is the alert message is printing every element in the form.

So, there must be something wrong with the “if” statement. I’ve tried several things and nothing seems to work. It seems the if statement always returns true no matter what the name of the element is.

Very lost.

Any thoughts ??

var q = thisform.elements;

for ( i = 0; i < q.length; i++ ) {
if (/^[REQUIRED_AgendaName|REQUIRED_TestListName|REQUIRED_ProcedureName]$/.test(q[i].name) ) {

alert(‘called ‘ + q[i].name); // debugging

if (/[‘”,]+|^s+|s+$/.test(q[i].value )) {
alert(msg);
q[i].focus();
q[i].select();
return false;
}
}

}

to post a comment
JavaScript

1 Comments(s)

Copy linkTweet thisAlerts:
@steelersfan88Mar 06.2004 — why don't you, if can't get the reg exp working, use the following:[code=php]var msg = "bad input"
var q = thisform.elements;
var required="NAME1,NAME2,NAME3"
var names = required.split(',')
var check = 0

for (var i=0;i<q.length;i++) {
check = 0
for(var j=0;j<names.length;j++) {
if(q[i].name == names[j]) {
check = 1
}
}
if(check == 1) {
alert('called ' + q[i].name); // debugging

if (/['",]+|^s+|s+$/.test(q[i].value)) {
alert(msg);
q[i].focus();
q[i].select();
return false;
}
}
}[/code]
in the script tags of course! and just change required to the names of what you want to be required.

If you want to validate by numbers rather than names, do this:[code=php]var msg = "bad input"
var q = thisform.elements;
var required="0,1,4"
var names = required.split(',')
var check = 0

for (var i=0;i<q.length;i++) {
check = 0
for(var j=0;j<names.length;j++) {
if(i == names[j]) {
check = 1
}
}
if(check == 1) {
alert('called ' + q[i].name); // debugging

if (/['",]+|^s+|s+$/.test(q[i].value)) {
alert(msg);
q[i].focus();
q[i].select();
return false;
}
}
}[/code]
×

Success!

Help @anguilla spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 6.17,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @nearjob,
tipped: article
amount: 1000 SATS,

tipper: @meenaratha,
tipped: article
amount: 1000 SATS,

tipper: @meenaratha,
tipped: article
amount: 1000 SATS,
)...