My requirement is that i needs to perform the validation for the input text which should not allow the special characters at start and end of the word and also it shouldn't allow two consecutive special characters in between the word.
For the above mentioned requirement i have found the regex and tested it on regex101.com and it's coming correct but when i wrote in the javascript i am not able to get the desired results.
The snippets are as follows:
$('input').bind('keypress', function (event) {
var re = new RegExp("^[a-z0-9](?!.*?[^\na-z0-9]{2}).*?[a-z0-9]$");
var key = String.fromCharCode(!event.charCode ? event.which : event.charCode);
if (key.match(re)) {
alert("Successful match");
} else {
alert("No match");
return false;
}
});
<input type="text">
But every time i am getting the result as no match. I am not getting where i am getting wrong.
Please help on this.
The JSFiddle link is : Demo for the Regex
Regex sample input - taken from some stackoverflow post
The issue was that you were matching on the most recent character the user inputted against the regex, rather than the whole value of the <input>.
Try this code instead:
$('input').bind('keypress', function(event) {
var re = new RegExp("^[a-z0-9](?!.*?[^/\na-z0-9]{2}).*?[a-z0-9]$");
// This is now set to the value of the whole <input> element
var key = $('input').val()
if (key.match(re)) {
alert("Successful match")
}
else {
alert("No match")
}
})
JSFiddle
Try this.
^[a-z0-9](?!.*?[^\na-z0-9]{2}).*?[a-z0-9]$
I'm making a form for my friend that required all visitor to fill a specific domain name.
What I want is, they've to write a link starting with https://specificname.com and continue with an ID. Example https://specificname.com/id/WordOrNumber . I need something like regex or validator to validate the link they've fill in the form.
This is the string that I am using for now.
case 'url':
if ('http://' === $value) $value = '';
if ($value && !preg_match('/^(https?|s?ftp):\/\/(((([a-z]|\d|-|\.|_|~|[\x{00A0}-\x{D7FF}\x{F900}-\x{FDCF}\x{FDF0}-\x{FFEF}])|(%[\da-f]{2})|[!\$&\'\(\)\*\+,;=]|:)*#)?(((\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5]))|((([a-z]|\d|[\x{00A0}-\x{D7FF}\x{F900}-\x{FDCF}\x{FDF0}-\x{FFEF}])|(([a-z]|\d|[\x{00A0}-\x{D7FF}\x{F900}-\x{FDCF}\x{FDF0}-\x{FFEF}])([a-z]|\d|-|\.|_|~|[\x{00A0}-\x{D7FF}\x{F900}-\x{FDCF}\x{FDF0}-\x{FFEF}])*([a-z]|\d|[\x{00A0}-\x{D7FF}\x{F900}-\x{FDCF}\x{FDF0}-\x{FFEF}])))\.)+(([a-z]|[\x{00A0}-\x{D7FF}\x{F900}-\x{FDCF}\x{FDF0}-\x{FFEF}])|(([a-z]|[\x{00A0}-\x{D7FF}\x{F900}-\x{FDCF}\x{FDF0}-\x{FFEF}])([a-z]|\d|-|\.|_|~|[\x{00A0}-\x{D7FF}\x{F900}-\x{FDCF}\x{FDF0}-\x{FFEF}])*([a-z]|[\x{00A0}-\x{D7FF}\x{F900}-\x{FDCF}\x{FDF0}-\x{FFEF}])))\.?)(:\d*)?)(\/((([a-z]|\d|-|\.|_|~|[\x{00A0}-\x{D7FF}\x{F900}-\x{FDCF}\x{FDF0}-\x{FFEF}])|(%[\da-f]{2})|[!\$&\'\(\)\*\+,;=]|:|#)+(\/(([a-z]|\d|-|\.|_|~|[\x{00A0}-\x{D7FF}\x{F900}-\x{FDCF}\x{FDF0}-\x{FFEF}])|(%[\da-f]{2})|[!\$&\'\(\)\*\+,;=]|:|#)*)*)?)?(\?((([a-z]|\d|-|\.|_|~|[\x{00A0}-\x{D7FF}\x{F900}-\x{FDCF}\x{FDF0}-\x{FFEF}])|(%[\da-f]{2})|[!\$&\'\(\)\*\+,;=]|:|#)|[\x{E000}-\x{F8FF}]|\/|\?)*)?(#((([a-z]|\d|-|\.|_|~|[\x{00A0}-\x{D7FF}\x{F900}-\x{FDCF}\x{FDF0}-\x{FFEF}])|(%[\da-f]{2})|[!\$&\'\(\)\*\+,;=]|:|#)|\/|\?)*)?$/iu', $value))
return frmd_error('Please enter a valid URL.', $elm['name']);
break;
This code work perfectly but it will accept all kind of domain name that the visitor fill up.
Please just reply with the regex or validator only because I'll not know what to edit .
I'm bad with coding.
If you want to ensure the URL entered matches a specific prefix, then you can skip the regular expressions and just test the substring, such as:
var validPrefix = 'https://example.com';
if (enteredUrl.substring(0, validPrefix.length) != validPrefix){
alert('Invalid URL.');
}
If you want to allow for minor variations on the URL such as with/without the WWW or http and https, then you can use a simple regex that defines those as optional parts.
var urlRegex = /https?:\/\/(www.)?example.com/;
if (!urlRegex.test(enteredUrl)){
alert('Invalid URL.');
}
If you need to validate the entire URL format rather than just the prefix, the regex will need to be extended based on whatever format criteria you need to match. Some regular expression tutorials should help you determine how to match what you need. To add an ID number after the domain for example you could do:
var urlRegex = /https?:\/\/(www.)?example.com\/\d+/;
if (!urlRegex.test(enteredUrl)){
alert('Invalid URL.');
}
if you prefix and input url is
var validPrefix = "validDomain.com";
var inputURL = "www.validDomain.com/context1";
then all you need to do is
if ( inputURL.indexOf( validPrefix ) == -1 )
{
alert( "No, input URL doesn't contain valid domain prefix" );
}
else
{
alert( "Yes, input URL contains valid domain prefix" );
}
I have a text box that is going to be validated in JavaScript upon click on the submit button.
Only the character 0-9 and a-f and A-F are allowed.
So g-z and G-Z as well as other characters such as punctuation or not allowed.
The code I have so far is:
function validate_form ( )
{
valid = true;
if ( document.form.input.value == [a-zA-Z_,.:\|] )
{
alert ( "You can only enter either 0-9 or A-F. Please try again." );
valid = false;
}
return valid;
}
Which doesn't seem to work.
I'm new to JavaScript so can any one please give me a hint as to where I'm going wrong?
We can actually clean this code up a lot. There's no need to keep track of valid as test() will provide us with the true or false value we're looking for. It's also a good deal easier in your case to keep a whitelist of acceptable characters rather than a blacklist. That is, we know every character we want, but can't possibly specify every character we don't want.
function validate_form() {
return /^[a-fA-F0-9]+$/.test(document.form.input.value);
}
Note that you can also use this to do a pre-check:
document.form.input.onkeyup = function() {
if (!validate_form()) {
alert("You can only enter either 0-9 or A-F. Please try again.");
}
};
the syntax is /^[a-zA-Z_,.:\|]+$/.test(document.form.input.value). Notice the ^ and $: without them, the test will pass even for strings that have only at least one allowed character.
The best way for validation is to not let the user, enter wrong character. Use this code (this is the jQuery version, but you can also convert it easily to JavaScript):
$('#inputFiledId').keyup(function(e){
// checking the e.keyCode here, if it's not acceptable, the return false (which prevents the character from being entered into the input box), otherwise do nothing here.
});
This is called pre-check. Please consider that you whatever you do in client-side, you should always check the values at the server also (have server-side validation) as there are multiple hacks around, like form-spoofing.
You could do something like this
$('input').keyup(function(){
var charac = /[g-zG-Z;:,.|_]/;
var result = charac.test($(this).val());
if(result == true){
alert('You can only enter either 0-9 or A-F. Please try again.');
}
})
http://jsfiddle.net/jasongennaro/GTQPv/1/
I would like to perform form validation using JavaScript to check for input field only to contain numeric characters.So far, the validation checks for the field not being empty - which works fine.However, numeric characters validation is not working.I would be grateful for any help.Many thanks.
<script type="text/javascript">
//form validation
function validateForm()
{
var x=document.forms["cdp_form"]["univer_number"].value
if (x==null || x=="")
{
alert("University number (URN) field must be filled in");
cdp_form.univer_number.focus();
return false;
}
else if (is_valid = /^[0-9]+$/.test(x))
{
alert("University number (URN) field must have numeric characters");
cdp_form.univer_number.focus();
return false;
}
}
</script>
<input type ="text" id="univer_number" maxlength="7" size="25" name="univer_number" />
Rather than using Regex, if it must only be numerals you can simply use IsNumeric in Javascript.
IsNumeric('1') => true;
IsNumeric('145266') => true;
IsNumeric('abc5423856') => false;
You need invert your regular expression (add ^ inside [0-9]):
/^[^0-9]+$/
Your test condition is a bit strange:
else if (is_valid = /^[0-9]+$/.test(x))
Why have the redundant comparison to is_valid? Just do:
else if (/^[0-9]+$/.test(x))
Though the regex you are using will match numerals and only numerals - you need to change it to match anything that is not a numeral - like this /^[^0-9]+$/.
Better yet, get rid of the regex altogether and use IsNumeric:
else if (!IsNumeric(x))
On your line that says else if (is_valid = /^[0-9]+$/.test(x)), you're doing a simple assignment instead of testing that it is actually matching the regex.
Your pattern will still accept this input <b>##$##123 or ad!##12<b>. Use this pattern I created:
/[a-zA-Z-!##$%^&*()_+\=\[\]{};':"\\|,.<>\/?]/
This pattern will check if it is alphabetic and special characters.
You need to test for the negation of the RegExp because you want the validation to alert upon failure, so just add ! in front of it:
else if (is_valid = !/^[0-9]+$/.test(x))
See example →
I know this is an old post but I thought I'd post what worked for me. I don't require the field to be filled at all but if it is it has to be numerical:
function validateForm()
{
var x=document.forms["myformName"]["myformField"].value;
if (/[^0-9]+$/.test(x))
{
alert("Please enter a numerical amount without a decimal point");
myformName.myformField.focus();
return false;
}
}
This question already has answers here:
How can I validate an email address in JavaScript?
(79 answers)
How can I validate an email address using a regular expression?
(79 answers)
Closed 8 years ago.
This code is always alerting out "null", which means that the string does not match the expression.
var pattern = "^\w+#[a-zA-Z_]+?\.[a-zA-Z]{2,3}$";
function isEmailAddress(str) {
str = "azamsharp#gmail.com";
alert(str.match(pattern));
return str.match(pattern);
}
If you define your regular expression as a string then all backslashes need to be escaped, so instead of '\w' you should have '\\w'.
Alternatively, define it as a regular expression:
var pattern = /^\w+#[a-zA-Z_]+?\.[a-zA-Z]{2,3}$/;
BTW, please don't validate email addresses on the client-side. Your regular expression is way too simple to pass for a solid implementation anyway.
See the real thing here: http://www.ex-parrot.com/~pdw/Mail-RFC822-Address.html
this is the one i am using on my page.
http://www.zparacha.com/validate-email-address-using-javascript-regular-expression/
/^[a-zA-Z0-9._-]+#[a-zA-Z0-9.-]+\.[a-zA-Z]{2,6}$/
I've been using this function for a while. it returns a boolean value.
// Validates email address of course.
function validEmail(e) {
var filter = /^\s*[\w\-\+_]+(\.[\w\-\+_]+)*\#[\w\-\+_]+\.[\w\-\+_]+(\.[\w\-\+_]+)*\s*$/;
return String(e).search (filter) != -1;
}
Sometimes most of the registration and login page need to validate email. In this example you will learn simple email validation.
First take a text input in html and a button input like this
<input type='text' id='txtEmail'/>
<input type='submit' name='submit' onclick='checkEmail();'/>
<script>
function checkEmail() {
var email = document.getElementById('txtEmail');
var filter = /^(([^<>()\[\]\\.,;:\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,}))$/;
if (!filter.test(email.value)) {
alert('Please provide a valid email address');
email.focus;
return false;
}
}
</script>
you can also check using this regular expression
<input type='text' id='txtEmail'/>
<input type='submit' name='submit' onclick='checkEmail();'/>
<script>
function checkEmail() {
var email = document.getElementById('txtEmail');
var filter = /^([a-zA-Z0-9_\.\-])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
if (!filter.test(email.value)) {
alert('Please provide a valid email address');
email.focus;
return false;
}
}
</script>
Check this demo output which you can check here
function checkEmail() {
var email = document.getElementById('txtEmail');
var filter = /^(([^<>()\[\]\\.,;:\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,}))$/;
if (!filter.test(email.value)) {
alert('Please provide a valid email address');
email.focus;
return false;
}
}
<input type='text' id='txtEmail'/>
<input type='submit' name='submit' onclick='checkEmail();'/>
if email invalid then give alert message , if valid email then no alert message .
for more info about regular expression
https://www.w3schools.com/jsref/jsref_obj_regexp.asp
hope it will help you
You may be interested in this question (or this one), which highlights the fact that identifying valid email addresses via regexps is a very hard problem to solve (if at all solvable)
with more simple regex
Here it is :
var regexEmail = /\w+([-+.']\w+)*#\w+([-.]\w+)*\.\w+([-.]\w+)*/;
var email = document.getElementById("txtEmail");
if (regexEmail.test(email.value)) {
alert("It's Okay")
} else {
alert("Not Okay")
}
good luck.
function isEmailAddress(str) {
var pattern =/^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/;
return pattern.test(str); // returns a boolean
}
Email validation is easy to get wrong. I would therefore recommend that you use Verimail.js.
Why?
Syntax validation (according to RFC 822).
IANA TLD validation
Spelling suggestion for the most common TLDs and email domains
Deny temporary email account domains such as mailinator.com
jQuery plugin support
Another great thing with Verimail.js is that it has spelling suggestion for the most common email domains and registered TLDs. This can lower your bounce rate drastically for users that misspell common domain names such as gmail.com, hotmail.com, aol.com, aso..
Example:
test#gnail.com -> Did you mean test#gmail.com?
test#hottmail.con -> Did you mean test#hotmail.com?
How to use it?
The easiest way is to download and include verimail.jquery.js on your page.
After that, hookup Verimail by running the following function on the input-box that needs the validation:
$("input#email-address").verimail({
messageElement: "p#status-message"
});
The message element is an optional element that displays a message such as "Invalid email.." or "Did you mean test#gmail.com?". If you have a form and only want to proceed if the email is verified, you can use the function getVerimailStatus as shown below:
if($("input#email-address").getVerimailStatus() < 0){
// Invalid email
}else{
// Valid email
}
The getVerimailStatus-function returns an integer code according to the object Comfirm.AlphaMail.Verimail.Status. As shown above, if the status is a negative integer value, then the validation should be treated as a failure. But if the value is greater or equal to 0, then the validation should be treated as a success.
You can also try this expression, I have tested it against many email addresses.
var pattern = /^[A-Za-z0-9._%+-]+#([A-Za-z0-9-]+\.)+([A-Za-z0-9]{2,4}|museum)$/;
It would be best to use:
var pattern = /^\w+#[a-zA-Z_]+?\.[a-zA-Z]{2,20}$/;
This allows domains such as: whatever.info (4 letters at the end)
Also to test, using
pattern.test("exampleemail#testing.info")
returns true if it works
http://www.w3schools.com/js/js_obj_regexp.asp
I have been using this one....
/^[\w._-]+[+]?[\w._-]+#[\w.-]+\.[a-zA-Z]{2,6}$/
It allows that + before # (xyz+abc#xyz.com)
Little late to the party, but here goes nothing...
function isEmailValid(emailAdress) {
var EMAIL_REGEXP = new RegExp('^[a-z0-9]+(\.[_a-z0-9]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,15})$', 'i');
return EMAIL_REGEXP.test(emailAdress)
}
http://jsfiddle.net/yrshaikh/xvd6H/
var emailRegex = /^[A-Z0-9_'%=+!`#~$*?^{}&|-]+([\.][A-Z0-9_'%=+!`#~$*?^{}&|-]+)*#[A-Z0-9-]+(\.[A-Z0-9-]+)+$/i;
if(emailRegex.test('yoursamplemail'))
alert('valid');
else
alert('invalid');
Simple but powerful email validation for check email syntax :
var EmailId = document.getElementById('Email').value;
var emailfilter = /^[\w._-]+[+]?[\w._-]+#[\w.-]+\.[a-zA-Z]{2,6}$/;
if((EmailId != "") && (!(emailfilter.test(EmailId ) ) )) {
msg+= "Enter the valid email address!<br />";
}
You should bear in mind that a-z, A-Z, 0-9, ., _ and - are not the only valid characters in the start of an email address.
Gmail, for example, lets you put a "+" sign in the address to "fake" a different email (e.g. someone#gmail.com will also get email sent to someone+else#gmail.com).
micky.o'finnagan#wherever.com would not appreciate your code stopping them entering their address ... apostrophes are perfectly valid in email addresses.
The Closure "check" of a valid email address mentioned above is, as it states itself, quite naïve:
http://code.google.com/p/closure-library/source/browse/trunk/closure/goog/format/emailaddress.js#198
I recommend being very open in your client side code, and then much more heavyweight like sending an email with a link to really check that it's "valid" (as in - syntactically valid for their provider, and also not misspelled).
Something like this:
var pattern = /[^#]+#[-a-z\.]\.[a-z\.]{2,6}/
Bearing in mind that theoretically you can have two # signs in an email address, and I haven't even included characters beyond latin1 in the domain names!
http://www.eurid.eu/en/eu-domain-names/idns-eu
http://haacked.com/archive/2007/08/21/i-knew-how-to-validate-an-email-address-until-i.aspx
You can add a function to String Object
//Add this wherever you like in your javascript code
String.prototype.isEmail = function() {
return !!this.match(/^\w+#[a-zA-Z_]+?\.[a-zA-Z]{2,3}$/);
}
var user_email = "test.email#example.com";
if(user_email.isEmail()) {
//Email is valid !
} else {
//Email is invalid !
}