I'm using a regex below to validate email to accept alphanumeric characters. It works in the following cases
1) Must contain atleast one alphabets
2) allow alphanumeric
3) allow special characters .-and _
Regular Expression:
/^([a-zA-Z0-9])(([a-zA-Z0-9])*([\._-])?([a-zA-Z0-9]))*#(([a-zA-Z0-9\-])+(\.))+([a-zA-Z]{2,4})+$/i
Cases:
1111#gmail.com - allow
aaaa#gmail.com - allow
aa1_aa#gmail.com - allow
Output expected:
1111#gmail.com - not allow because it does not contain alphabets before #
aaaa#gmail.com - allow
a1#gmail.com - allow
1a#gmail.com - allow
aa1_aa#gmail.com - allow
Hers is jsfiddle Demo
Your regex will do the job, just add this at the beginning
(?=[^#]*[A-Za-z])
making your final regex like this:
/^(?=[^#]*[A-Za-z])([a-zA-Z0-9])(([a-zA-Z0-9])*([\._-])?([a-zA-Z0-9]))*#(([a-zA-Z0-9\-])+(\.))+([a-zA-Z]{2,4})+$/i
(?=exp) is positive look-ahead. It will try to find the expression without taking it into match. look-ahead actually matches characters, but then gives up the match.
(?=[^#]*[A-Za-z]) : will match [^#]*[A-Za-z], meaning anything other than # followed by a alphabet. So actually it will match if at least one alphabet is present in the part before #
You canrefer this for look-ahead and look-behind
Here is the JavaScript code:
var email_to_check = "1111#gmail.com";
email_check=email_to_check.substring(0,email_to_check.lastIndexOf("#"));
var isnum = /^\d+$/.test(email_check);
var email_regex = /^([a-zA-Z0-9!##$%^&*(){}|:"<>?\/';\\+\-~]*#[a-zA-z]+\.[a-zA-z]+)$/;
email_test = email_regex.test(email_to_check);
if(isnum){
alert("You must enter aleast an Alphabet !")
}else{
if(email_test){
/* code if email is right :) */
alert("This is corrrect email !")
}else{
alert("Enter valid email address !");
}
}
Remove the special char which you don't want in your checklist.
Related
In our project, we use this regular expression to validate emails:
"^([\w-\.]+)#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,7}|[0-9]{1,3})(\]?)$"
But it allows non English characters.
For example:
"مستخدم#mail.com"
"userمحمد#mail.com"
"userName#خادم.com"
are valid emails.
How to add another rule to this expression to limit inputs to English letters only?
You can omit the alternation | in your pattern, and there is an optional closing bracket \]? which I think you don't need in an email address.
This part in the regex with Javascript and C# [\w-\.] does not seem to be a valid range in a character.
Instead of using \w you can use [A-Za-z0-9] to match ASCII chars and digits 0-9 in C#.
If you don't want to match consecutive dots or hyphens, you can use a pattern like this and then extend it if you have more characters that you want to allow:
^[A-Za-z0-9]+(?:[.-][A-Za-z0-9]+)*#[A-Za-z0-9]+(?:[.-][A-Za-z0-9]+)*\.[a-z]{2,}$
Regex demo
Note that this only validates an email address of this format.
Can do like this
string[] StrInputNumber = { "pradeep1234#yahoo.in", "مستخدم#mail.com'", "userمحمد#mail.com", "userName#خادم.com" };
Regex ASCIILettersOnly = new Regex(#"^[\P{L}A-Za-z]*$");
foreach (String item in StrInputNumber) {
if (ASCIILettersOnly.IsMatch(item)) {
Console.WriteLine(item + " ==> valid");
}
else {
Console.WriteLine(item + " ==>not valid");
}
}
Output
for some basic explanation about regex Click Here
You can use this website to test your regular expression
If you don't need to keep your current expression you can use this one instead:
^[A-Z0-9._%+-]+#[A-Z0-9.-]+\.[A-Z]{2,4}$.
I tested it with your examples and it works as you want.
I am trying to find if a string has valid domain names or not in JavaScript.
As per requirement, these are my valid and invalid domain names.
Valid Domain:
api.google.com
*.api.google.com
*.api.google.user.com
tenant.my.centrify-kibble.net
aws.logs.security.stark.tony.com
myest.r-project.org
login-dev.qacloudad.com
Invalid Domain:
https://google.com
https://www.google.com
https://*.google.com
*.google.com/
*google.com/
*google.com
google.com.
login-dev.qacloudad.com.
login-dev.qacloudad.com.*
.login-dev.qacloudad.com
below code is working as expected for both valid as well as invalid domain except "*google.com".
I am still getting valid expression as result for "*google.com"
How can I fix this RegEx?
var fqdn = "aws.logs.security.stark.tony.com";
if (fqdn.match("^(?!-)[A-Za-z0-9-*]+([\\-\\.]{1}[a-z0-9]+)*\\.[A-Za-z]{2,6}$")) {
console.log("Matched");
}
else{
console.log("Not Matched");
}
You may use the following pattern:
^(?:\*\.)?[a-z0-9]+(?:[\-.][a-z0-9]+)*\.[a-z]{2,6}$
Regex demo.
Breakdown:
^ - Beginning of string.
(?:\*\.)? - Match an optional "*." literally.
[a-z0-9]+ - One or more alphanumeric characters.
(?:[\-.][a-z0-9]+)* - A hyphen or a dot followed by one or more alphanumeric characters to be matched zero or more times.
\.[a-z]{2,6} - A dot followed by between two and six letters.
$ - End of string.
JavaScript test:
var fqdn = "aws.logs.security.stark.tony.com";
if (fqdn.match(/^(?:\*\.)?[a-z0-9]+(?:[\-.][a-z0-9]+)*\.[a-z]{2,6}$/)) {
console.log("Matched");
}
else{
console.log("Not Matched");
}
To support upper-case letters, you can either (re-)add A-Z to the character classes or simply append the i flag at the end:
fqdn.match(/^(?:\*\.)?[a-z0-9]+(?:[\-.][a-z0-9]+)*\.[a-z]{2,6}$/i)
// ^
I am new to angular js. I have created a login screen. I need to validate my password. it should contain one special character from -'$#£!%*#?&' and at least one letter and number. As of now it accepts all special characters without any limitations. I have following code
if (vm.newpassword_details.password.search("^(?=.*?[A-Za-z])(?=.*?[0-9])(?=.*?[$#£!%*#?&]).{8,}$")) {
var msg = "Password should contain one special character from -'$#£!%*#?&' and at least one letter and number";
alert(msg);
}
Note that your current regex imposes 4 types of restriction:
At least one ASCII letter ((?=.*?[A-Za-z])),
At least one digit ((?=.*?[0-9])),
At least one specific char from the set ((?=.*?[$#£!%*#?&]))
The whole string should have at least 8 chars (.{8,})
The . in .{8,} can match any char other than line break chars.
If you plan to restrict the . and only allow users to type the chars from your sets, create a superset from them and use it with RegExp#test:
if (!/^(?=.*?[A-Za-z])(?=.*?[0-9])(?=.*?[$#£!%*#?&])[A-Za-z0-9$#£!%*#?&]{8,}$/.test(vm.newpassword_details.password)) { /* Error ! */ }
See the regex demo
I'm attempting to validate a field name to match a certain format in JavaScript using Regular Expressions.
I need the string inputted to resemble this:
word\word\word
So anything inputted can't be blank, and it must be three words seperated by a backslash.
This is the code i'm working with, but i'm not sure if the pattern is the right syntax?!!
function validateResourceName() {
//get posted resource name value
var inputString = document.getElementById("resourceName").value;
//should be in the word\word\word format
var pattern=/[a-Z|/\\/|a-Z|/\\/|a-Z\s]/;
//If the inputString is NOT a match
if (!pattern.test(inputString)) {
alert("not a match");
}
else
{
alert("match");
}
}
Any help will be very appreciated!!!
If by word you mean the English letters a-z in upper or lower case, then:
/^(?:[a-z]+\\){2}[a-z]+$/i
That says:
^ Beginning of string
(?:...) Non-capturing group
[a-z]+ One or more letters a-z (or A-Z because of the i flag at the end). If you also want to allow some other characters, just add them to the [a-z] after the z. If you want to allow hyphens, add \- to it (you need the backslash, depending on where you put the hyphen, so I just always include it). Note that this is very English-centric, and even in English sometimes people write borrowed words with their non-English letters, such as résumé.
\\ Backslash
{2} Repeated twice
(Then another word)
$ End of string
The issues with your expression are:
[a-Z] Is invalid because the range is out of order (Z comes before a). If it were valid (or if you wrote [Z-a]), it would matches everything between Z and a, which isn't just a-z and A-Z
\\/ Requires a backslash and then a slash
| is an alternation (this or that)
\s is whitespace
Try /^[a-z]+\\[a-z]+\\[a-z]+$/
function validateResourceName() {
//get posted resource name value
var inputString = document.getElementById("resourceName").value;
//should be in the word\word\word format
var pattern=/^[a-z]+\\[a-z]+\\[a-z]+$/
//If the inputString is NOT a match
if (!pattern.test(inputString)) {
alert("not a match");
} else {
alert("match");
}
}
If you want to allow the word matching to be case insensitive;
`/^[a-z]+\\[a-z]+\\[a-z]+$/i`
If you want to be a bit more broad with what you define as a 'word', and allow it to consist of alphanumeric characters and underscore;
`/^\w+\\\w+\\\w+$/i`
you can just use this \w+\\\w+\\\w+
or
[a-zA-Z]+(\\[a-zA-Z]+){2}
This should do it
^\w+\\\w+\\\w+$
In javascript
if (/^\w+\\\w+\\\w+$/.test(subject)) {
// Successful match
} else {
// Match attempt failed
}
Try this one , See the Regex fiddle for regex demo and Jsfiddle for the code demo
Regex
/(\w)*\\(?!\\)(\w)*\\(?!\\)(\w)*(?!\\)/g
Javascript
function validateResourceName(string) {
var pattern = /(\w)*\\(?!\\)(\w)*\\(?!\\)(\w)*(?!\\)/g;
if (!pattern.test(string)) {
alert("not a match");
} else {
alert("match");
}
}
I am using jquery validation plugin for validating my input fields.
I have a field that should accept:
a) letters [a-zA-Z]
b) letters with numbers [a-zA-Z0-9]
c) no special characters
So:
ADFad1334 or 43545SFDDFdf454fgf : is correct, since we have letters and numbers
asdadadASD : is correct, since we have only letters
12312342 : NOT correct, since its only numbers
sdff23424#$ : NOT correct, since there are special characters (in this example # and $)
The code i used is the one below:
$.validator.addMethod("atLeastAletter", function(value) {
return /^[a-zA-Z]*$/img.test(value) || /^[a-zA-Z0-9]*$/img.test(value);
},"Must contain at least a letter and/or number(s). No other characters are allowed");
And then:
$('#RegistrationForm').validate({
rules: {
fieldname: {
atLeastAletter: true
},
.....
The problem with this regular expression is that if the input is only numbers (ex. 3434224), it will accept it and pass validation.
What is the problem?
Thanks in advance.
or this pattern
^(?=\S*[a-zA-Z])[a-zA-Z0-9]+$
Demo
^ # Start of string/line
(?= # Look-Ahead
\S # <not a whitespace character>
* # (zero or more)(greedy)
[a-zA-Z] # Character Class [a-zA-Z]
) # End of Look-Ahead
[a-zA-Z0-9] # Character Class [a-zA-Z0-9]
+ # (one or more)(greedy)
$ # End of string/line
/^\w*[a-zA-Z]+\w*$/
That should match any string with only letters and numbers, but it must contain at least one letter.
sadAddsa // Pass
98463298 // Fail
jdsH98sd // Pass
987Fkjd89 // Pass
jfk!jhj // Fail
kjhgh8768!# // Fail
A8 // Pass
8S // Pass
B // Pass
7 // Fail
B_bkfd86jh // Fail (Using the regex in the edit)
Edit: As Alpha Bravo pointed out. This will match underscores too. If you don't want underscores /^[a-zA-Z0-9]*[a-zA-Z]+[a-zA-Z0-9]*$/will only match letters and numbers, only if it contains one letter.
If you want want to go with all HTML5 look at this fiddle: http://jsfiddle.net/bud68oho/2/
This fiddle uses the required and pattern attributes to validate the form. The required attribute does not allow the form to post if the input is not filled in. The pattern attribute allows you to implement regex for matching. If the input does not meet the requirements of the regex then the form will not post.
The only gotcha with this approach is browser compatibility. Make sure to test this method with your target browsers. The above example works in the latest version of IE and Chrome, I am unable to do any further testing.
/^[a-zA-Z0-9]*$/img.test("1") is true, so just take with two regexp for both:
return /^[a-zA-Z]*$/img.test(value) || (/[a-zA-Z]/img.test(value) && /^[a-zA-Z0-9]*$/img.test(value))
or like this:
return /^[a-zA-Z]*$/img.test(value) || (/^[a-zA-Z0-9]*$/img.test(value) && !/^[0-9]*$/img.test(value))
Notice: If you put i after the regexp (img) you just have to put a-z or A-Z, it's not case sensitive.
Ohter notice: you allow empty strings "" with those regexps.
I think you may need to do a positive alphanumeric check and a negative check for the numeric only case.
$.validator.addMethod("atLeastAletter", function(value) {
return /^[a-zA-Z0-9]+$/img.test(value) && ! /^[0-9]+$/img.test(value)
},"Must contain at least a letter and/or number(s). No other characters are allowed");