Question

This email validation regex (from jquery.validate) works fine, except I think that it would be a little easier on the user if pre and post spaces were allowed. I am already trim()ing with php, once I get the form submitted.

valid = this.optional(element) || /^[a-zA-Z0-9.!#$%&'*+\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/.test(value);

I tried adding \s* but no dice.

    valid = this.optional(element) || /\s*^[a-zA-Z0-9.!#$%&'*+\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$\s*/.test(value);
Was it helpful?

Solution

If you want to accept whitespace, \s* has to go between the ^...$-anchors:

valid = this.optional(element) || /^\s* (snipped) \s*$/.test(value);

Alternatively you can just trim() the string before testing.

valid = this.optional(element) || /^ (snipped) $/.test(value.trim());
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top