Avatar of earwig75
earwig75
 asked on

How to validate all fields with a certain name

I use the below IF statement to validate a single text field input box called "PhoneNum" on submit. It allows either blank, or 10 digits. I need to apply this logic to all fields with the word "PhoneNum" in the text box name. The fields are added dynamically, so I need to look for all input boxes with "Phonenum" in the name.

I'd like to keep it in an if statement, and use jQuery to do this, with something like: $("[name*=PhoneNum]").....

Could someone assist?
var PhoneNum = $("#PhoneNum").val();

	    if(/^(\d{0}|\d{10})$/.test(PhoneNum) == false) {
	    	alert("All Phone Number fields can only contain 10 digits.");
	    	$( "#PhoneNum" ).focus();
	        return false;
	    	}

Open in new window

jQueryJavaScriptHTML

Avatar of undefined
Last Comment
Big Monty

8/22/2022 - Mon
Big Monty

try this:

$([name*="PhoneNum"]).each(function(){
var PhoneNum = $( this .val();

	    if(/^(\d{0}|\d{10})$/.test(PhoneNum) == false) {
	    	alert("All Phone Number fields can only contain 10 digits.");
	    	$(  this  ).focus();
	        return false;
	    	}
});

Open in new window

earwig75

ASKER
This doesn't seem to work. Below is what my function looks like.

<script type="text/javascript">
	window.onload = function() {
    document.getElementById("Submit").onclick = function() {
$([name*="PhoneNum"]).each(function(){
var PhoneNum = $( this .val();

	    if(/^(\d{0}|\d{10})$/.test(PhoneNum) == false) {
	    	alert("All Phone Number fields can only contain 10 digits.");
	    	$(  this  ).focus();
	        return false;
	    	}
});
</script>

Open in new window

Big Monty

can you provide the html mark up for a few of the fields?
Experts Exchange has (a) saved my job multiple times, (b) saved me hours, days, and even weeks of work, and often (c) makes me look like a superhero! This place is MAGIC!
Walt Forbes
earwig75

ASKER
<input type="text" name="PhoneNum">
<input type="text" name="aPhoneNum">
<input type="text" name="PhoneNum3">
Big Monty

looks like a missing ) on line 5, it should be:

var PhoneNum = $( this ).val() ;
earwig75

ASKER
Thanks but that still didn't fix it.

I ended up having to create a new function outside of the submit, and then returning the function in the submit.
⚡ FREE TRIAL OFFER
Try out a week of full access for free.
Find out why thousands trust the EE community with their toughest problems.
ASKER CERTIFIED SOLUTION
Big Monty

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
GET A PERSONALIZED SOLUTION
Ask your own question & get feedback from real experts
Find out why thousands trust the EE community with their toughest problems.
Big Monty

working example