regex (javascript) allow \w but not a single specified word - javascript

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

Related

Regex Behaves Differently on HTML Pattern than on an Express Backend

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})+$/'

Prevent Smart Quotes on HTML5 Input

Had an annoying issue with my web application more recently. Using HTML5, a user can create an account with a login ID. The ID can contain pretty much any character. A user will enter an account ID, for example
Bob'sAccount
And their device (unknown to them) turns the ' into a "smartquote" with the ` style apostrophe
So now their account is created (with a smartquote in the user ID). However, if they try to log in using a device which doesn't automatically create smart quotes, they try to log in using the standard apostrophe, and since it's a different character, their account is not found.
I'm sure I could limit the characters a user can enter for an account ID, but I would rather just prevent the smartquotes from happening in the first place.
Is there a way to disable "smartquotes" in an HTML5 input field?
If you know what the character is turning into, just replace it with a regular quote before you submit the form.
str
.replace(/[\u2014]/g, "--") // emdash
.replace(/[\u2022]/g, "*") // bullet
.replace(/[\u2018\u2019]/g, "'") // smart single quotes
.replace(/[\u201C\u201D]/g, '"'); // smart double quotes
This is just an example, i know it's tedious but that's one way to do it. Check out: https://asna.com/us/tech/kb/doc/remove-smart-quote for a script that has a lot of other special characters that are replaced to serve your same function

Auto-format Driver's License using Javascript?

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.

Restrict input some personal information

I want to check what users type in Textarea.
Actually, how can I restrict typing phone numbers and e mail addresses in description box?
So for example:
Hi, I am selling a Bugatti Veyron
Age: 2010
Color: Black
You can contact me on 066/656-656 or 055646646
or via mail mesell#domain.com
If someone tries to enter something like this I want to automatically remove
personal contact details.
So, please help, how can I do it?
Use Regex and do something like this :
Here's an example (jsFiddle)
HTML
<textarea></textarea><br>
<button>Test</button><br>
<span class="result"></span>
Javascript:
function validateEmail(email) {
var re = /^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
$('.result').html(re.test(email));
if(re.test(email)){
$('.result').html("Contain email");
} else {
$('.result').html("Do not contain email");
}
}
$('button').click(function(){
validateEmail($('textarea').val());
});
Note that I only look for email. But you can use other Regex to look for phone, you just have to search for something like "javascript regex phone" on Google.
you can try Regex as suggested, but take into consideration it's very hard to stop a phone number from being entered(unless you stop ALL numbers or know the exact form of the number taking place).
For example, stopping a xxx-xxxxxxx number is easy, but the user can type each digit with a space after it, which makes it much harder to stop(unless you again remove the option to type numbers.
As for emails, a simple regex to find a # followed by some text, a dot and 2 or 3 characters normally finds emails pretty easily. be advised people can still be creative in the way they put their emails(AT instead of # for example).
this should all be done server side, you can use javascript on the clientside to make it UI friendly.
For email validation:
<input type="email" name="email">
Here is an example: http://www.w3schools.com/html/tryit.asp?filename=tryhtml5_input_type_email
For Phone number validation:
use regex, it should be straight forward though.
Or just try isNAN(value) where value is the phone number enterd, will tell you if this is a number of not and then you can also put a check on number of digits.
Hope this helps!

Angular.js ng-pattern strange behaviour

I have been working on a form that accepts Twitter parameters such as # and # to populate a Twitter feed.
With Angular.js I had planned to use the built in ng-pattern directive to validate the input before saving, however the validation is acting extremely strangely. It marks a "valid" string as invalid on every 2nd character of the input while typing.
Its quite hard to explain the exact behaviour so heres a Plunker.
For completeness I will add my input field with the strange ng-pattern here:
<input type="text" ng-pattern="/(^|\s)#(\w+)|(^|\s)#(\w+)/g" ng-model="foo" name="foo"/>
It's because of the global matching with the g option, it works if you take it out.
Calling test or exec multiple times involves state:
As with exec (or in combination with it), test called multiple times on the same global regular expression instance will advance past the previous match.
Basically it's trying to move on to another match, but can't find one:
a = /#(\w+)$/g;
> /#(\w+)$/g
a.exec("#test")
> ["#test", "test"]
a.exec("#test")
> null

Categories