1

I'm trying to create a sign up form which is only open to students currently studying at a UK university, so need to ensure the email address they enter ends in .ac.uk.

I have the following JS function but it's not working at all.

function valUniEmail()
{

var email = document.getElementById('contactFormEmail');
if (email.innerHTML.match(^[\w!#$%&'*+/=?^`{|}~-]+(?:\.[\w!#$%&'*+/=?`{|}~-]+)*@(?:[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?\.)+(?:\.ac\.uk)$`)
                {
                document.getElementById('tick').style.display = 'display;'
                }
                else
                {
                document.getElementById('cross').style.display = 'none;'
                }


}

Any ideas why this might not be working?

Thanks

Andy Kaufman
  • 761
  • 3
  • 9
  • 21
  • 1
    Sorry, but I could send directly a POST request to your server to bypass this security. You have to also implement this on your server side script. If you want to do it "right", use this [regex](http://stackoverflow.com/a/719543/) and use a second match like this `\.ac\.uk$` to check if there is `.ac.uk` at the end. – HamZa Apr 28 '13 at 12:20
  • 1
    Don't have access to the server, but I'm not dealing with any computer science students, so don't think they'll manage to bypass it haha. Although, thanks I do appreciate your point about security. – Andy Kaufman Apr 28 '13 at 13:27
  • The display properties value should be "block" and "none", not "display;" and "none;" – powerbuoy Apr 28 '13 at 12:33
  • Using the es6 endsWith(), you can write the if statement as if(email.endsWith('ac.uk')) {}, https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/String/endsWith – Ryan White Oct 13 '15 at 19:30

1 Answers1

2

You should quote the regexp with /.../ and escape any / chars with \/ like this:

/^[\w!#$%&'*+\/=?^`{|}~-]+(?:\.[\w!#$%&'*+\/=?`{|}~-]+)*@(?:[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?\.)+(?:ac\.uk)$/
Aleksei Zyrianov
  • 2,294
  • 1
  • 24
  • 32
  • Hello, thanks for your answer. The function now runs, but whatever email address I enter, even those that should pass the condition, fail it. – Andy Kaufman Apr 28 '13 at 12:27
  • @AndyKaufman It seems like the problem was in the fact that we checked for a `\.` before `ac.uk` at the twice, so an address `test@foo.ac.uk` would pass. I've fixed this in the answer. – Aleksei Zyrianov Apr 28 '13 at 12:34