April 26, 201016 yr I have a form text entry field for entering a URL. The field should be used to enter a URL containing a .mp3 file extension. I want to check the form field before the form is submitted, to ensure it contains the text ".mp3" at least once in the field - if it dosen't, a popup message would appear. I found this tutorial - http://javascript.about.com/library/blvalid04.htm - however I have not been able to get it to work. Does anyone have any suggestions or demos of ways I can get it working? Thanks Zach
April 26, 201016 yr Hi there, there are a few ways you could do this: If you just want to check that the string has 'mp3' in it then var str = 'mymusicfile.MP3'; var pattern = /mp3/i; // case insensitive regex if (str.search(pattern) == -1) { //string doesn't contain 'mp3' } or if you want to check for 'mp3' as the last 3 characters of the string: var str = 'mymusicfile.MP3'; var match = 'mp3'; if (str.substr(str.length - 3).toLowerCase() != match) { forces lowercase comparison // string doesn't end with 'mp3' } Both will allow you to compare case insensitive incase a file is named with an uppercase extension
April 29, 201016 yr Author Thanks for responding. I have included your code in a function: <script type="text/javascript"> function mp3check() { var str = 'mymusicfile.MP3'; var match = 'mp3'; if (str.substr(str.length - 3).toLowerCase() != match) { forces lowercase comparison // string doesn't end with 'mp3' // } } </script> I presume I need to add something to the form field such as onblur="mp3check()" in order to get the check to work? e.g. <input type="text" name="entryURL" id="entryURL" size="50" onblur="mp3check()" /> I would like to add a message that pops up when mp3 is not found - how would I add that in? Thanks Zach
April 30, 201016 yr Author If anyone can help finalize this, I would appreciate it very much. Thanks Zach
April 30, 201016 yr Hey Zack, just in case you haven't seen my PM: function mp3check(str) { var match = 'mp3'; if (str.substr(str.length - 3).toLowerCase() != match) { alert('your message here'); } } <input type="text" name="entryURL" id="entryURL" size="50" onblur="mp3check(this.value)" />
Create an account or sign in to comment