I have the following regex pattern on an HTML input field, which is supposed to hold an email address:
<input type="text" pattern="^\w+([.-]?\w+)*#\w+([.-]?\w+)*(\.\w{2,4})+$" /><br>
I furthermore have the same regex on an Express (JavaScript) backend using the following:
var re-email = new RegExp("^\w+([.-]?\w+)*#\w+([.-]?\w+)*(\.\w{2,4})+$")
if (!re-email.test(email)) {
validation = false
}
Although the regex are exactly the same, a specific test input is evaluated as true on the front-end while as false on the backend.
Why is this?
Solution (found after the initial post):
Instead of using "new RegExp" (which is not working) as above, include the Regex within forward slashes as below (which works).
var re-email = /^\w+([.-]?\w+)#\w+([.-]?\w+)(.\w{2,4})+$/
Probably not the answer you are after (not vue.js specific)...
Email address input validation should usually be completed like so:
<input type="email" name="" value="" required />
Specifying the correct "type" to an input field also adjusts input keyboards on mobile devices to make inputting an email address easier.
Your regular expression is poorly written and leads to "catastrophic backtracking" as well as not actually supporting valid email addresses.
Email address validation is generally complex, see this answer and associated question:
https://stackoverflow.com/a/201378/406712
You can also find the HTML email address validation equivalent regular expression in the HTML spec:
https://html.spec.whatwg.org/multipage/input.html#valid-e-mail-address
Also note you failed to escape the characters in the string, the first instance being the \w which without escaping the \ will appear as simply w.
Escaped the string it more like this:
'/^\\w+([.-]?\\w+)#\\w+([.-]?\\w+)(.\\w{2,4})+$/'
Related
I'm having a problem with my regex validation code. I'm trying to figure out how can I validate a vehicle license plate number. The code that I wrote is listed below this message. This is written down in React inline code and I've written down two different regex expressions and both of the come out to be false. The license plate number should be in this format XX-NNNN-XX.
X = Letter
N = Number
const [licencePlate, setLicencePlate] = useState('');
var ValidateLicencePlate = /^[A-Z][A-Z]-[0-9][0-9][0-9][0-9]-[A-Z][A-Z]$/g ;
var regex = /^[A-Z]{2}-[0-9]{4}-[A-Z]{2}$/g ;
<input name="licence-plate" type="text" className="feedback-input" maxLength='10' onChange={(e) => setLicencePlate(e.target.value.toUpperCase())} placeholder="XX-NNNN-XX"/>
This regex can solve the problem.
let regex = /^[A-Z]{2}-\d{4}-[A-Z]{2}/gi
This regex will match two alphabet at the beginning, four digits at the middle and two alphabet at the end.
You can use regex as following
<input pattern="/^[A-Z]{2}-\d{4}-[A-Z]{2}/g"/>
You can put your regex in the pattern attribute of the input element. I do not see you are using regexps yo have defined anywhere in your listing.
<input pattern={regex}/>
If you have a regex constraint to validate against it may be better and more comfortable to use Constraint Validation API.
<input pattern="your regex here"/>
Browser already validates everything in form elements if you constraint them with various ways like patter attribute and unless you tell it not to validate. But still I see many code bases trying to do the validation themselves. It is unnecessary since there is a way platform itself supports and does itself.
I have an input box entering US Driver's License number. However, I want it to restrict to this format (A1234567) when typing.
I have searched for this but I can only find RegEx.
<input id="id">
<script>
</script>
Expected to have an auto formatted input box for Driver's License number.
(format: A1234567)
Thank you very much for your help.
Modern browsers have form validation functionality built into them. They can check a regex pattern for you. Minimally, all you have to do is set the pattern attribute.
Let's first work out the expression you need. I assume from your format:
The first character is always a capital A.
There will be 7 digits after that, 0 through 9.
For that, we use the following regex:
A[0-9]{7}
Basically, this just requires a literal A, followed by 7 characters in the set 0-9.
Now to use that in HTML:
<input type="text" name="license" pattern="A[0-9]{7}">
The browser will show some generic error for input not matching. We can do better than that though. That's where the Constraint Validation API comes in. First, wrap that input in a <form> element:
<form>
<input type="text" name="license" pattern="A[0-9]{7}">
</form>
Now, let's add some JavaScript code check the validity every time there is input (effectively when a character is entered, or content is pasted):
const licenseEl = document.querySelector('input[name="license"]');
licenseEl.addEventListener('input', (e) => {
e.target.setCustomValidity(''); // Clear any previous failed invalid messages
e.target.checkValidity();
});
Finally, add our custom message if the input is invalid:
licenseEl.addEventListener('invalid', (e) => {
e.target.setCustomValidity('Enter a valid license number.');
});
You end up with something like this:
As a bonus, you're automatically compatible with screen readers, alternative input devices, future interfaces, etc.
Here's a JSFiddle so you can play around with it yourself: https://jsfiddle.net/k7g2bj9L/1/
For older browsers, you may want a polyfill. And of course, always validate your input server-side. The browser can be entirely bypassed.
I'm creating an email field in my html, can I only accept one #?
For example email:
chong!#$#gmail.com - should invalid because of there are others special characters included
or
ch#ng#gmail.com - should also be invalid because there are two #'s.
The only accepted special character should only be one #, how do I do this in javascript/jquery?
Sorry I really don't know much in regex. Or is there another way to validate an email format?
You can use the following regex in your input:
<input type="email" pattern="[a-zA-Z0-9.]+\#[a-zA-Z0-9.]+\.[a-zA-Z]+" />
This pattern avoid the user input an 'email' that don't fits with the email standard but also avoid limited the number of characters input in the name of user to 64 characters and the number of characters in the domain too.
^[A-Z0-9._%+-]{1,64}#(?:[A-Z0-9-]{1,63}.){1,125}[A-Z]{2,63}$
Some other patterns for validate numbers, numbers and letters and just letters:
^[0-9]+$
^[a-zA-Z0-9]+$
^[a-zA-Z]+$
Also you can use regular expression with javascript like this
Validate email address in JavaScript? and this other page its really useful for check if your regex pattern works correctly
http://regexr.com/
Try using this. It will open up a popup explaining the error if format is incorrect:
<form>
<input pattern="[a-zA-Z0-9.]+\#[a-zA-Z0-9.]+\.[a-zA-Z]+" title="Write your error here" />
<input type="submit" />
</form>
Hope this helps.
I've been banging my head against the wall and trying to google a solution for several hours with my "problem".
I need a javascript (html5 input) regex pattern, in a registration form which hasn't been submitted yet, which allows normally: ^[\w]+$ but after a submit, if the page which processes the post finds that username is already been taken, takes user back to the registration form (which is now pre-filled with the values he/she typed).
This time that "username" input field should have a pattern which don't allow user to type that same username again, but everything else will do fine.
I've played around on http://regex101.com/#javascript and came up with 100% the opposite I wanted:
^(?=[\w]*)test(?=[\w]*)$
I've been testing my pattern with string:
abctestabc
test
dfea
atest
testa
Regex I'm trying to obtain should match on everything else on my testing string, except for "test" and my pattern matches ONLY for that one.
Second pattern I came up with (which I shortly thought was what I wanted) was:
^(?:([\w]+test[\w]+)|([\w]+test|(test[\w]+)))$
..but didn't take long since I noticed that this only allows user to input:
*test
*test*
test*
..but nothing without "test" included.
First time on form:
<input type="text" name="username" pattern="^[\w]+$" />
Secound time should be:
<input type="text" name="username" pattern="**PATTERN HERE**" value="test" />
So please Stackoverflow, Pimp my regex!
user3548238, do you mean this?
^(?!test$)\w+$
This pattern will allow \w+, like before, but it will not allow "test".
This is accomplished with a lookahead.
Why don't you start pimping here ?
http://www.infotuts.com/live-username-availability-checker-and-password-strength-indicator-with-jquery-and-ajax/
DEMO
I have a signup form where user can enter, along other information, company's name and company's URL ID. Now, I'd like to suggest "URL ID" to the user so when he types "name", "URL ID" should be based on this input (very similar to Facebook "name" and "username" paradigms). I should also mention that user can manually type in "URL ID" for corrections after it was suggested.
It's important to mention here that based on this question I was able to successfully implement server-side validation for the "name" field using the following Regex expression (client-side validation is not needed):
/^[\p{L}\p{N}]+(?:[- \'\x26][\p{L}\p{N}]+| [\x26] [\p{L}\p{N}]+)*$/iu
There are certain rules that must be applied to URL IDs:
Valid characters are: both lower- and uppercase letters (Latin only), numbers, dashes, underlines and dots
Must begin and end with a letter or number
Must not have more than one special character (dash, underline or dot) in row
Can have multiple special characters in "URL ID"
As an example of what's valid and what's not, here are some examples:
Valid inputs
myusername
my.username12
my.user20_name
8-user-name-my
Invalid inputs
myuser20name.
_myusername10
my..username
myuser-.name
To make the long story short, two things need to be done:
while user is typing in/pasting the "name" field, I need to take input on-the-fly, keep only allowed characters discarding the rest, and filling in the "URL ID" field with the filtered input
while user is typing in/pasting the "URL ID" field, I need input to validates against the rules mentioned above so that for example typing in "my.user-" would be ok (although it would fail the server-side validation due to "-" being the last character), but typing additional "-" would not be allowed
I guess I only need the valid Regex expression, I'm able to code the rest myself. Any help would be appreciated.
I do not know if I understand all the rules, but according to his examples this regexp validates exactly what you need!
^[a-zA-Z0-9]+([-_\.][a-zA-Z0-9]+)*[a-zA-Z0-9]$
http://regexr.com?36f5b