entering regular expressions in javascript - javascript

Im trying to add this regular expression ^[a-zA-Z0-9,.&#-]{1-45}#[a-zA-Z]{1-45}.[a-z]{3}$ to validate email addresses to this javascript code.
if(email=="" || email==null)
{
document.getElementById("em_error").innerHTML="*You must enter your Email Address";
error=true;
return false;
}
else
document.getElementById("em_error").innerHTML="";

You can use the match function.
if(email=="" || email==null || !email.match(/^[a-zA-Z0-9,.&#-]{1-45}#[a-zA-Z]{1-45}.[a-z]{3}$/,i))
NOTE
Please review your pattern, because there should be longer and shorter TLD then 3 characters, like .museum, .eu, .nowanytldcantakenformoney

Change your code as shown below (using RegExp.test function):
...
var re = /^[a-zA-Z0-9,.&#-]{1-45}#[a-zA-Z]{1-45}.[a-z]{3}$/;
if (!email || !re.test(email)) { // if the input value is empty or doesn't match the needed pattern
document.getElementById("em_error").innerHTML="*You must enter your Email Address";
error = true;
return false;
} else {
document.getElementById("em_error").innerHTML="";
}
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/test

Related

Regex modification needed to enforce atleast one special symbol character

I'm using the following regex for a password field :
/^(?=.*[a-zA-Z])(?=.*\d)(?=.*[!##$%^&*()_+])[A-Za-z\d][A-Za-z\d!##$%^&*()_+]{7,63}$/
I'd like to enhance it to force atleast one number , one alphabet and one special symbol.
I'm using the following JavaScript code to validate the same :
function validatePassword()
{
var password = document.getElementById('password').value;
var userID = document.getElementById('user_ID').value;
var regexPattern = /^(?=.*[a-zA-Z])(?=.*\d)(?=.*[!##$%^&*()_+])[A-Za-z\d][A-Za-z\d!##$%^&*()_+]{7,63}$/ ;
if(regexPattern.test(password))
{
if(userID === password )
{
$('#status').text( 'User id is same as password . Please choose a more secure password');
return false;
}
else if(password === reverse(userID))
{
$('#status').text( 'Password is reverse of user id . Please choose a more secure password');
return false;
}
else
{
return true;
}
}
else
{
return false;
}
}
How do I do it ?
Thanks.
Instead of using regex you can check like this also.
Just replace
if(regexPattern.test(password))
with
if(regexPattern.test(password) && /[a-zA-Z]/.test(password) && /[0-9]/.test(password) && /[\!\#\#\$\%\^\&\*\(\)\_\+]/.test(password) )
Check string if it is valid password, contain alphabet, number and special character ( if you want more add in range ).

How to do email address validation using Javascript (without JQuery)? [duplicate]

This question already has answers here:
How can I validate an email address in JavaScript?
(79 answers)
Closed 7 years ago.
I'm trying to do an email address validation for an input text field, however, it must only submit if the entry is not null and has the # char in it
Example 1 is the one that works, however, it excludes the need for the # char
function emailvalidation() {
var x=document.forms["input"]["email"].value;
if (x==null || x=="") {
alert("Input email address, please!");
return false
}
Example 2 which does not work, but is how I imagine it would be written
function emailvalidation() {
var x=document.forms["input"]["email"].value;
var email = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/;
if (x<>null || x<>"" && x.value.match(email)) {
alert("Input email address, please!");
return true
} else {
alert("Input email address, please!");
return false
}
}
Anyone have any ideas? Thank you though, preferably without JQuery! Thanks!
Another email validation.
function isValidEmailAddress(emailAddress) {
var pattern = new RegExp(/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))#((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i);
return pattern.test(emailAddress);
};
You have a couple of logical problems in your solution.
Firstly, the condition is that x is not null and x is not an empty string and x matches the pattern.
Secondly, <> is the wrong comparator for javascript; use != or !==.
Thirdly, as pointed out by putvande x is already the element's value, so x.value.match() is probably causing you issues.
function emailvalidation() {
var x = document.forms["input"]["email"].value;
var email = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/;
if (x !== null && x !== "" && x.match(email)) {
return true;
} else {
alert("Input email address, please!");
return false;
}
}
Thank you all for this! The solution was a mixture of all of the answers! Though, here is the final solution! Needed a new reg expression and !==
Thank you all though, from a JS beginner, it is really appreciated
function emailvalidation() {
var x=document.forms["input"]["email"].value;
var email = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/;
if (x !== null && x !== "" && x.match(email)) {
return true
} else {
alert("Input email address, please!");
return false
}
}
Based on your first script and requirements, one solution without regex, and one with.
Note that a text-inputfield only returns strings.
Email-addresses must have something before the #, so we check if an # appears after the first character (using indexOf we don't require a regex). Also, if we have found the # that means the string was not empty!!
If the # is at the same position as the last # and this position is smaller then the total string-length, this gives us a true or false value, which we can instantly return.
If none of the three conditions is met, then we alert our error-message. alert returns undefined (which in itself coerces to false in javascript, but) which we force to a boolean false using double not !! and return that value.
The second example follows the same logic, but uses a regex.
function emailvalidation(){ //without regex
var s=document.forms.input.email.value
, x=s.indexOf('#');
return( x>0 && x===(x=s.lastIndexOf('#')) && x<s.length-1
) || !!alert("Input email address, please!");
}
function emailvalidation(){ //with regex
return /^[^#]+#[^#]+$/.test(document.forms.input.email.value) || !!alert("Input email address, please!");
}
<form name="input">
<input name="email" type="text" />
</form>
<button onclick="alert(emailvalidation())">test</button>
Final note, it's good that you are liberal in accepting email-addresses, since trying to do a good job in regex is long and difficult, see for example this regex: http://www.ex-parrot.com/pdw/Mail-RFC822-Address.html
There is simply no 100% reliable way of confirming a valid email address other than sending an email to user and and waiting for a response. See also https://softwareengineering.stackexchange.com/questions/78353/how-far-should-one-take-e-mail-address-validation
If you do try to regex 'valid email-addresses' then inform your employer that you are going to cost him business/clients/cash!!!

Javascript Email Validation Specific Domain

I'm trying to get someone to use a specific email domain of #mail.fhsu.edu. Here is my Validation code.
function validateFHSUEmail(inputField, helpText) {
if (inputField.value.length == 0) {
if (helpText != null) {
helpText.innerHTML = "Please Enter a Value";
}
return false;
} else {
var reg = /^[a-z.]+#mail.fhsu.edu$/;
if (!reg.test(inputField)) {
if (helpText != null) {
helpText.innerHTML = "Please Enter FHSU Email";
}
Am I calling it wrong or what because no matter what it returns false.
You're testing the variable "inputField", which apparently is a reference to a DOM element. You want inputField.value in the test.
edit Note the comment wherein it's pointed out that your regex should use \. for the periods in the domain name.
If you want valid email and specific domain try this regex:
/^(([^<>()\[\]\.,;:\s#\"]+(\.[^<>()\[\]\.,;:\s#\"]+)*)|(\".+\"))#domain.com$/

how validate an email that allows specific number of dots before and after # symbol

var val_em=document.add_indus_detail_form.txt_email.value;
var atpos=val_em.indexOf("#");
var dotpos=val_em.lastIndexOf(".");
if(val_em!='')
{
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=val_em.length)
{
alert("Not a valid e-mail address");
return false;
}
}
i use this condition to check the email validation that user enters in the textbox how i can validate it like it allows 3 or 4 or any specific numbers of dot allow (ex abc.abc.abc.abc#abc.abc.com) before and after the # but do not allow that dots together (ex: abc#abc...com). also do not allow the spaces in email how it will be have you any idea for this type of validation..
I would suggest a regex for this
function validateEmail(email){
var emailReg = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(#((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(#\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);
var valid = emailReg.test(email);
if(!valid) {
return false;
} else {
return true;
}
}
call the function validateEmail whenever you need....
Validations in JavaScript are useless. The user can turn off JS or maybe you encounter a browser who cant even understand JS. This makes your page vulnerable to attacks. So NEVER use JS for validating user inputs.
What you want is RegEx or many if-conditions together with string-functions. My approach: Use a For-Loop, go through the string one by one, check the current character and the one after it. Like this:
for($i = 0; $i < strlen($string); $i++) {
if(substr($string, 0, 1) == '.' {
//do something
}
}

jQuery Tools Validator - regex test - exclude just letters

i'm trying to validate a field to include everything except letters but the following only works on the first character i enter. So if i enter '123a' the test method returns true.
$.tools.validator.fn("input#Phone", "Please enter a valid phone number.", function(input, value) {
var pass;
var rgx = /[^a-z]/gi;
if ( rgx.test(value)
|| (value == "")
|| (value == $(input).attr("placeholder"))) {
$(input).removeClass("invalid");
pass = true;
} else {
$(input).addClass("invalid");
pass = false;
}
return pass;
}
You're only matching against a single character.
/^[^a-z]$/i
This ensures that the entire string is non-letters.
for only numeric:
RegExp(/^[^a-zA-Z]$/i)
for phone number you can use
RegExp(/^[0-9 -()+]{6,20}$/i)

Categories

Resources