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

earwig75Asked:
Who is Participating?

[Webinar] Streamline your web hosting managementRegister Today

x
 
Big MontyConnect With a Mentor Senior Web Developer / CEO of ExchangeTree.org Commented:
try this fiddle, it works for me:

https://jsfiddle.net/bigmonty/xym4vcur/1/
0
 
Big MontySenior Web Developer / CEO of ExchangeTree.org Commented:
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

0
 
earwig75Author Commented:
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

0
The new generation of project management tools

With monday.com’s project management tool, you can see what everyone on your team is working in a single glance. Its intuitive dashboards are customizable, so you can create systems that work for you.

 
Big MontySenior Web Developer / CEO of ExchangeTree.org Commented:
can you provide the html mark up for a few of the fields?
0
 
earwig75Author Commented:
<input type="text" name="PhoneNum">
<input type="text" name="aPhoneNum">
<input type="text" name="PhoneNum3">
0
 
Big MontySenior Web Developer / CEO of ExchangeTree.org Commented:
looks like a missing ) on line 5, it should be:

var PhoneNum = $( this ).val() ;
0
 
earwig75Author Commented:
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.
0
 
Big MontySenior Web Developer / CEO of ExchangeTree.org Commented:
working example
0
All Courses

From novice to tech pro — start learning today.