JQuery validate website address input - javascript

I have an input text for a website address and I would like to validate it.
Examples of of what should be allowed are: www.somesite.com or .net or .org or anything valid for a website address.
Probably should use jQuery or just plain Javascript

Disclaimer : this is an extremely
naive implementation of a url
validation written in regex literal
javascript for the purpose of
explaining the thought behind such an
endeavor, this code is not intended
for production use in any capacity.
URL validation using regular expressions:
The following code will work for a cross section of cases. You will want to verify that those cases match your need. Urls are wide and varied creatures including possible usage of utf-8 characters not covered in the basic set below. For those cases you will want to investigate more about regex (totally worth doing in any capacity for javascript development anyway).
var urls = ['www.someurl.com', // true
'www.someurl.net', // true
'google.org', // true
'not a url', // false
'someone#funky.com', // false
'http://www.yahoo.com', // true
'https://www.clutter.org', // true
'ftp://test.fail', // false
'http://this.is.a/path/to/my/resource.html', // true
'adress-with-hyphens.org']; // true
for( var i = 0, url; url = urls[i++]; ){
console.log(url, /^(https?:\/\/)?([\w\d\-_]+\.)+\/?/.test(url));
}
to explain this code:
/ starts the regex literal.
( opens a selection group.
http is a string to search for.
s? makes the s part of the string optional.
: is a search of the colon character.
\/ is the escape character followed by the character to search for (/), this is useful in many cases.
)? makes the group optional.
The next group contains a lookup for any word, digit, hyphen or underscore character (one or more +), followed by a . (\.). followed by an optional /. / at the end closes the regular expression literal. test is a method on any regular expression object to see if a string passes it. The string to test is given as the only argument.

You want to use regular expressions.
Regular expressions are a pattern matching technology designed to search Regular Languages. What this means is you can use a Regular Expression to find and match many different things that fit your desired pattern.
A great place to start learning regex (short for Regular Expressions) at regular-expressions.info
They have amazing guides to get you started
Once you learn about them you will understand why this pattern
[www]?\..*?\.(com|net|org)
means and why it is not a great pattern to use to match a website although it would work.
Good luck and happy hunting

I noticed your title references jQuery - and while I assume this question is dead thought I'd post this for anyone else coming along. This jQuery plugin is simple to use and pretty powerful. While a plugin is overkill to validate a single field it can be helpful if you have other validation (including required fields) on the same form. The below example is pulled from the docs. After initing the plugin you simply add classes of what validation to include. You can create customs one if you need it but its a little more complex.
http://bassistance.de/jquery-plugins/jquery-plugin-validation/
Usage is simple:
$("#commentForm").validate();
form:
<form class="cmxform" id="commentForm" method="post" action="">
<p>
<label for="cname">Name</label>
<em>*</em><input id="cname" name="name" size="25" class="required" minlength="2" />
</p>
<p>
<label for="cemail">E-Mail</label>
<em>*</em><input id="cemail" name="email" size="25" class="required email" />
</p>
<p>
<label for="curl">URL</label>
<em> </em><input id="curl" name="url" size="25" class="url" value="" />
</p>
<p>
<label for="ccomment">Your comment</label>
<em>*</em><textarea id="ccomment" name="comment" cols="22" class="required"></textarea>
</p>
<p>
<input class="submit" type="submit" value="Submit"/>
</p>
</form>
And thats it XD

$.ajax({url: webpage ,type:'HEAD',error:function(){
alert('Oops !');
}});

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

Regex not recognizing input value for vehicle license plate

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.

Textbox to accept only one #

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.

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

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

What did I do wrong here? [Javascript Regex]

So I am writing a registration form and I need the display name to be only numbers, letters and underscores.
Have a look at my code and tell me what I'm doing wrong.
<form method="post" action="/" onsubmit="return check_form()">
<input type="text" id="display-name" name="display-name" maxlength="255" />
<input type="submit" />
</form>
<script type="text/javascript">
<!--
var name_regex = /^([a-zA-Z0-9_])+/
function check_form()
{
if (!name_regex.test(document.forms[0].elements[0].value))
{
document.forms[0].elements[0].focus()
alert("Your display name may only contain letters, numbers and underscores")
return false
}
}
-->
</script>
It's obviously been trimmed down to not include anything not related to the problem but even this snippet doesn't work.
Your regex
/^([a-zA-Z0-9_])+/
Looks for
Start of string(check), followed by
1 or more letters, numbers, or underscore (check)
And then whatever comes after it doesn't matter. This regex will match anything at all so long as it begins with a letter, number, or underscore
If you put a $ at the end, then it will work - $ matches 'end of string', so the only way it can match is if there are only numbers, letters, and underscores between the start and end of the string.
/^([a-zA-Z0-9_])+$/
Secondly, I'd suggest using document.getElementById('display-name').value instead of document.forms as it won't break if you rearrange the HTML, and is more 'the commonly accepted standard of what to do'
My regexp would go along the lines of: /^[a-zA-Z0-9_]+$/
edit: I think it's the lack of a line end $ that makes it fail.
What does "doesn't work" mean? Does it reject valid display names? Does it accept invalid display names? Which ones?
Per #Annan, leaving off the $ would make the regexp accept invalid display names like abc123!##.
If the code is rejecting valid display names, it may be because the parentheses are being matched literally instead of denoting a group (I'm not sure of the quoting convention in JS).
A simpler way to write it still would be
var name_regex = /^([a-z0-9_])+$/i;
Even simpler:
var name_regex = /^\w+$/;
I tested your script and meddled with the javascript. This seem to work:
<form method="post" action="/" onsubmit="return check_form()">
<input type="text" id="display-name" name="display-name" maxlength="255" />
<input type="submit" />
</form>
<script type="text/javascript">
<!--
var name_regex = /^([a-zA-Z0-9_])+$/;
function check_form()
{
if (!name_regex.test(document.forms[0].elements[0].value))
{
document.forms[0].elements[0].focus();
alert("Your display name may only contain letters, numbers and underscores");
return false;
}
}
-->
</script>
Sorry guys I should have been more specific. Whenever I added spaces the values were still being accepted. The dollar sign $ did the trick!
By 'not working' I take it you mean it is letting invalid entries through (rather than not letting valid entries through).
As #Annan has said, this would probably be due to the lack of the $ character at the end of the expression, as currently it only requires a single valid character at the start of the value, and the rest can be anything.

Categories