In a textbox a user needs to give 5 US Zipcodes separated by comma.
Now I need to validate it in following way:
1st Whether the five words are typed by User must be separated by comma.
2nd Each word is a valid US Zipcode.
Yes, there are plenty of regex for US ZipCode validation but in my case I need to do some more with regex which I am not familiar with. Any help will be appreciated.
I'm using a jquery selector, but you can do document.getElementById or whatever. And you'll need
error = false;
var zip_codes = $('input').val().split(',');
if (zip_codes.length!=5) error = true;
else {
for (i=0; i<zip_codes.length; i++) {
if (!(/(^\d{5}$)|(^\d{5}-\d{4}$)/.test(zip_codes[i])))
error = true;
}
}
Basically we split the string on commas, check if there are 5, if so, we check if each thing between commas is a valid zip code. At the end of the function, if error is true, don't submit the form. If it's false, you are good to go.
Related
I can't create an input in which the first character entered must be a letter, and the following characters can be only letters or only one underscore in a row
i have an input and following javascript code for it:
var nick = document.getElementById('donate-nickname');
function validatenick(evt) {
var regex = /^[a-zA-Z][a-zA-Z_]*$/;
if(!regex.test(nick.value)) evt.preventDefault();
}
nick.onkeydown = validatenick;
nick.onpaste = validatenick;
but it doesn't work
Some issues:
You are not assigning visited to onkeydown, but instead execute it. (You fixed this after I posted this answer)
input.value will reflect the input as it is before the key was processed, so the validation check comes too early.
The regex does not implement the logic you describe
I would suggest a regex where you perform a negative look-ahead for a double underscore. Also make it allow empty input as else the user cannot delete the last character that remains in the input.
For responding to all input methods, use the input event. Then to cancel the edit that would break the pattern, you could keep track of the most recent input that was still valid, and when there is a violation of the pattern, roll back to that value:
var input = document.getElementById('nickname');
var lastValid = "";
function validate(evt) {
var regex = /^(?!_)(?!.*?__)[A-Za-z_]*$/;
if(!regex.test(input.value)) {
input.value = lastValid;
}
lastValid = input.value;
}
input.oninput = validate;
<input id="nickname">
As a side note, I would personally not block edits like that: users may wrongly think their keyboard is malfunctioning. It is better practice to let the user type what they want, but accompany it with feedback (coloring, an error message, ...).
I have one requirement in form.My form has textbox field "DEA License number".textbox must allow user to enter alphabet only for first two characters and numbers only after two characters.I want to achieve this functionality using javascript.Note:-I dont want validation but avoid user inputting
Have you tried using regex?
Take a look at this post which has a very similar goal: RegEx pattern any two letters followed by six numbers
Try use some of masked textbox.
For example:
https://css-tricks.com/input-masking/
http://digitalbush.com/projects/masked-input-plugin/
You can easily test this with a regex:
function isValid(str) {
return /^[a-zA-Z]{2}\d+$/.test(str);
}
I am not quite sure what you mean by "I dont want validation but avoid user inputting." If you mean that you don't want the user to be able to type an invalid character, this could theoretically be done with an input event handler:
var oldValue = "";
document.getElementById("test").addEventListener("input", function(e) {
var value = e.target.value;
if ((value.length <= 2 && /^[a-zA-Z]*$/.test(value)) || value.length > 2 && /^[a-zA-Z]{2}\d+$/.test(value)) oldValue = value
else e.target.value = oldValue;
})
However, you'd still need to validate it when it's submitted since the user could've entered an incomplete value.
I am working to validate a string of email addresses. This pattern works fine if there is only one email address:
var pattern = /^\w+#[a-zA-Z_]+?\.[a-zA-Z]{2,3}$/;
But if I have two email addresses separated by space or by a newline, then it does not validate. For example:
xyz#abc.com xyz#bbc.com
or
xyz#abc.com
xyz#bbc.com
Can you please tell me what would be a way to do it? I am new to regular expressions.
Help much appreciated! Thanks.
Try this RegEx
/^\s*(?:\w+#[a-zA-Z_]+?\.[a-zA-Z]{2,3}\b\s*)+$/
In the above image, everything inside Group 1 is what you already had. I have added a word ending and spaces.
It will match "xyz#abc.com", " xyz#bbc.com ", "xyz#abc.com xyz#bbc.com" and email addresses in multiple lines also.
Update
I got the RegEx for Email from http://www.regular-expressions.info/email.html and I have used it in my expression. You can find it below:
/^\s*(?:([A-Z0-9._%+-]+#[A-Z0-9.-]+\.[A-Z]{2,4})\b\s*)+$/i
Change the ^ and $ anchors to word boundaries, \b.
/\b\w+...{2,3}\b/
You should also note that the actual specification for email addresses is extremely complicated and there are many emails that will fail this test -- for example those with multiple periods in the domain. May be okay for your purposes, but just pointing it out.
try this
function validateEmail(field) {
var regex=/\b[A-Z0-9._%+-]+#[A-Z0-9.-]+\.[A-Z]{2,4}\b/i;
return (regex.test(field)) ? true : false;
}
function validateMultipleEmailsCommaSeparated(value) {
var result = value.split(" ");
for(var i = 0;i < result.length;i++)
if(!validateEmail(result[i]))
return false;
return true;
}
You might consider simply splitting the whole string into an actual array of email addresses, instead of trying to validate the entire thing at once. This has the advantage of allowing you to point out in your validation message which address failed.
uld look like this:
var emailRegex = /^[A-Z0-9._%+-]+#(?:[A-Z0-9-]+\.)+[A-Z]{2,4}$/i; // http://www.regular-expressions.info/email.html
var split = form.emails.value.split(/[\s;,]+/); // split on any combination of whitespace, comma, or semi-colon
for(i in split)
{
email = split[i];
if(!emailRegex.test(email))
{
errMsg += "The to e-mail address ("+email+") is invalid.\n";
}
}
Your best regular expression for multiple emails accepts all special characters
(-*/+;.,<>}{[]||+_!##$%^&*())
Best Regular Expression for multiple emails
/^([A-Z0-9.%+-]+#[A-Z0-9.-]+.[A-Z]{2,6})*([,;][\s]*([A-Z0-9.%+-]+#[A-Z0-9.-]+.[A-Z]{2,6}))*$/i
I am working with an email validation script and all is well, apart from if a user tries to enter an address with only two characters in the domain such as test#me.com or temp#ip.com
The validation then fires an error, I have looked through but cant see where this behaviour is being targeted, the code is below...
function validate_youremail()
{
var isvalidemailflag = 0;
if(jQuery("#property_mail_email").val() == '')
{
isvalidemailflag = 1;
}else
if(jQuery("#property_mail_email").val() != '')
{
var a = jQuery("#property_mail_email").val();
var filter = /^[a-zA-Z0-9]+[a-zA-Z0-9_.-]+[a-zA-Z0-9_-]+#[a-zA-Z0-9]+[a-zA-Z0-9.-]+[a-zA-Z0-9]+.[a-z]{2,4}$/;
//if it's valid email
if(filter.test(a)){
isvalidemailflag = 0;
}else{
isvalidemailflag = 1;
}
}
if(isvalidemailflag)
{
youremail.addClass("error");
youremailInfo.text("Please Enter valid Email Address");
youremailInfo.addClass("message_error2");
return false;
}else
{
youremail.removeClass("error");
youremailInfo.text("");
youremailInfo.removeClass("message_error");
return true;
}
Its probably staring me straight in the face but its been a long day :) Can anyone point me in the right direction?
#[a-zA-Z0-9]+[a-zA-Z0-9.-]+[a-zA-Z0-9]+
Means "#" then "one or more of those characters" then "one or more of those characters and dots and hyphens" then "one or more of those characters".
That makes it "at least three characters".
You probably want to change the middle part (of that snippet) to be zero or more (i.e. * instead of +).
The expression is still broken though. The problem that jumps out at me is that it rejects email addresses with a + in the part before the #.
Email Validation as per RFC2822 standards.
Pattern: /[a-z0-9!#$%&'*+/=?^_{|}~-]+(?:.[a-z0-9!#$%&'*+/=?^_{|}~-]+)*#(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?/g
Source: RegExr
Mind you, the RFC2822 standard doesn't allow upper case characters in an email address, but you can easily adapt it for your own purposes.
I recommend you to use another regular expression.
This regular expression has been extracted from the PHP source code written in C.
/^(?!(?:(?:\x22?\x5C[\x00-\x7E]\x22?)|(?:\x22?[^\x5C\x22]\x22?)){255,})(?!(?:(?:\x22?\x5C[\x00-\x7E]\x22?)|(?:\x22?[^\x5C\x22]\x22?)){65,}#)(?:(?:[\x21\x23-\x27\x2A\x2B\x2D\x2F-\x39\x3D\x3F\x5E-\x7E]+)|(?:\x22(?:[\x01-\x08\x0B\x0C\x0E-\x1F\x21\x23-\x5B\x5D-\x7F]|(?:\x5C[\x00-\x7F]))*\x22))(?:\.(?:(?:[\x21\x23-\x27\x2A\x2B\x2D\x2F-\x39\x3D\x3F\x5E-\x7E]+)|(?:\x22(?:[\x01-\x08\x0B\x0C\x0E-\x1F\x21\x23-\x5B\x5D-\x7F]|(?:\x5C[\x00-\x7F]))*\x22)))*#(?:(?:(?!.*[^.]{64,})(?:(?:(?:xn--)?[a-z0-9]+(?:-+[a-z0-9]+)*\.){1,126}){1,}(?:(?:[a-z][a-z0-9]*)|(?:(?:xn--)[a-z0-9]+))(?:-+[a-z0-9]+)*)|(?:\[(?:(?:IPv6:(?:(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){7})|(?:(?!(?:.*[a-f0-9][:\]]){7,})(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){0,5})?::(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){0,5})?)))|(?:(?:IPv6:(?:(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){5}:)|(?:(?!(?:.*[a-f0-9]:){5,})(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){0,3})?::(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){0,3}:)?)))?(?:(?:25[0-5])|(?:2[0-4][0-9])|(?:1[0-9]{2})|(?:[1-9]?[0-9]))(?:\.(?:(?:25[0-5])|(?:2[0-4][0-9])|(?:1[0-9]{2})|(?:[1-9]?[0-9]))){3}))\]))$/i
.test('temp#ip.com');
I think many people have done some similar development tasks before:
I would like to check the people's email address whether only match #tomtom.com or #stream.com.
Currently, I have two solutions in my mind:
Using indexof() function
var checkTomTomEmail=eo.data.username.indexOf("#tomtom.com");
var checkStreamEmail=eo.data.username.indexOf("#stream.com");
if (checkTomTomEmail >0 || checkStreamEmail >0 )
{
//Run the login code
}
Else
{
//Please login with your tomtom or stream email
}
Using match
var patt1=/#tomtom.com/gi;
var patt2=/#stream.com/gi;
var checkTomTomEmail=eo.data.username.match(patt1);
var checkStreamEmail=eo.data.username.match(patt2);
if(indexOf(checkTomTomEmail)> 1 ||indexOf (checkStreamEmail)>1)
{
//Login
}
I still think I do not consider all the detail yet. Any suggestions?
Thanks
Perhaps if people are only allowed to enter emails for those two addresses you should only collect the username and then allow them to choose #tomtom.com or #stream.com using radiobuttons.
If you still want to go the javascript route then your regex can be combined into a single statement
var emailPatt=/#(tomtom|stream).com/gi;
if(emailPatt.test(eo.data.username))
{
//Login
}
How about this...
var emailRegex = /^([0-9a-z])+#(tomtom|stream)\.com$/ig;
if (emailRegex.test(emailRegex)) {
// Login
}
Instead of performing a .match(...) - Which you'll get a string back, we can perform a .test(...) to see if anything matches.
This pattern guarantees the following:
The "username" part of the email address must at least have a SINGLE character (For example, a#stream.com)
Username must be composed of a digit or an alphabet (Upper/Lower case - Doesn't matter because of the /i at the end)
Input must contain the entire email address without leading or tailing spaces. For example, " user#tomtom.com " will fail, it'll only accept "user#tomtom.com".)
You can customize this further by, saying, making sure username must have at least 3 characters, you can use underscore or dashes in the email address, etc.
To answer your question, both solutions won't work. Reasons:
User can enter "tom#tomtom.com Hello", and it'll pass both of your validation.
Specifically on solution #2, the dot '.' is a Regex-reserved character, it means it'll match anything, so, if the user enters " #tomtom1com", it'll pass...
More on Regex: http://www.regular-expressions.info/reference.html