I'm setting up a form and in it I've already coded verifying that there is an entry in the email form box as you can see here
function checkMailing(){
//if we want to refer to the email field - which has the name 'email' - we would use the form variable (created above), as such:
//theForm.email
//you this with the name of any field iside of the form
//alert(theForm.email.value);
//use an if statement to check the value of the form
var mailingVal = theForm.mailing.value
mailingVal = trim(mailingVal);
if(mailingVal == "" ){
//error message
//add a dropshadow to the field (to highlight it)
theForm.mailing.style.boxShadow = "0px 0px 6px #01FFFF";
//from the form field, go up to the parent (the div with the class 'formbox', then inside of that for the div with the class 'fieldInfo', and change the text contents to be an error message
setMessage(theForm.mailing, "error", "You must enter an address");
/*theForm.email.parentNode.querySelector("div").innerHTML = "You must enter an email!";
theForm.email.parentNode.querySelector("div").className = "error";*/
}else{
//if the user entered an email (or in this anything) give them positive feedback
theForm.mailing.style.boxShadow = "";
setMessage(theForm.mailing, "correct", "Perfect");
/*theForm.email.parentNode.querySelector("div").innerHTML = "Perfect)"
theForm.email.parentNode.querySelector("div").className = "correct";*/
}
}
However I need it to also validate that it is a CERTAIN email address and not just any email address. For example it must be an #gmail.com address and not an #hotmail.com or #anythingelse.com. Any guidance would be appreciated thank you!
You can use regex:
if (mailingVal && mailingVal.match(/#gmail\.com$/i)) {
// it's gmail
}
A better approach might be to use a regex which makes sure that the string to match ends with #gmail.com
var re = /#gmail\.com$/i;
if(re.exec(mailingVal) !== null) {
// the test passed!
}
This will ensure that the string ends with #gmail.com and does not contain any extra characters after the .com
Using that regex, someone#gmail.com will match, but someone#gmail.comm will not. As will someone#Gmail.com or someone#GMAIL.COM (and so on) because of the /i switch.
If you wanted it to only match case-sensitively, just remove the /i switch, so the regex would read like
var re = /#gmail.com$/
Update
Here is the regex solution in your code, changed the exec to test (which just returns true or false, depending on whether the regex matches or not):
function checkMailing(){
//if we want to refer to the email field - which has the name 'email' - we would use the form variable (created above), as such:
//theForm.email
//you this with the name of any field iside of the form
//alert(theForm.email.value);
//use an if statement to check the value of the form
var mailingVal = theForm.mailing.value,
re = /#gmail\.com$/i;
mailingVal = trim(mailingVal);
if(!re.test(mailingVal)){
//error message
//add a dropshadow to the field (to highlight it)
theForm.mailing.style.boxShadow = "0px 0px 6px #01FFFF";
//from the form field, go up to the parent (the div with the class 'formbox', then inside of that for the div with the class 'fieldInfo', and change the text contents to be an error message
setMessage(theForm.mailing, "error", "You must enter an address");
/*theForm.email.parentNode.querySelector("div").innerHTML = "You must enter an email!";
theForm.email.parentNode.querySelector("div").className = "error";*/
} else {
//if the user entered an email (or in this anything) give them positive feedback
theForm.mailing.style.boxShadow = "";
setMessage(theForm.mailing, "correct", "Perfect");
/*theForm.email.parentNode.querySelector("div").innerHTML = "Perfect)"
theForm.email.parentNode.querySelector("div").className = "correct";*/
}
}
This should work for you. I do have one question about the trim() function you are using. What is it? Is there a library you are using, or is the trim function something you wrote? I would just use String.prototype.trim to remove whitespace from the beginning and end of the mailingVal.
If you know wich exactly mail vendor you want to check, then try this one:
if (mailingVal.length && mailingVal.indexOf('#gmail.com') > -1 ) console.log('that is gmail!');
You also may need to put your string to lover case to be sure that 'Gmail' is also valid
mailingVal = mailingVal.toLowerCase()
UPD:
as metioned in comments, this case will make mails like 'wut#gmail.commadot' also valid.
To prevent that you can try this check:
mailingVal = mailingVal.split['#'];
if (mailingVal.length > 2) {
console.log('not Valid email');
} else {
if (mailingVal[1].toLowerCase() === 'gmail.com') console.log('Bingo!');
}
Related
I have an email and a password input with required and instead of "Please fill out this field.", I want a message in another language.
I found from relevant questions that I must use the setCustomValidity() but I don't know how to implement it correctly since the examples were using inline JavaScript or jQuery or they changed the message for one input.
While using this code:
function validate() {
const inputs = document.getElementsByTagName('input');
for (let input of inputs) {
let validityState = input.validity;
if (validityState.valueMissing) {
input.setCustomValidity('Παρακαλώ συμπλήρωσε το πεδίο.');
} else if (validityState.typeMismatch) {
input.setCustomValidity('Πρέπει να υπάρχει ένα «#»!')
} else {
input.setCustomValidity('');
}
input.reportValidity();
}
}
document.getElementsByTagName('input').innerHTML = validate();
I was able to change the language but I noticed that when I typed on the email input, the validity message would stay even if the input wasn't empty!
The task that I'm working on has an div where you need to input your email. It's a simple task, it only needs to check if the email is missing # and a period, and then display certain text, nothing too complicated. But, I've tried using the includes() function and the Chrome Console thing displays an error saying that varname.includes() it's not a function.
Here's part of my HTML code where the JavaScript should take place after using onlick:
<div class="warning"> </div>
<div class="email">
<input class="mail" type="email" name="mail" placeholder="your email">
<input class="send" type="submit" name="send" value="SEND" onclick="checkEmail()">
</div>
Bascially, what the JavaScript code needs to do is:
If it's missing #, write "missing #" in the warning div.
If it's missing ., write "missing ." in the warning div.
If it's missing both # and ., write "Your email address is not correct!" in the warning div.
If the email meets both criteria, it makes an alert saying "You are in!"
As I mentioned, I tried using includes() within an if, which didn't work, and I have no clue what else would work here. I know basics like how to make an alert or write text, I just don't know how to make the code check if the characters are there or missing. Any help on this would be greatly appreciated!
const toCheckFor = ["#", "."] // Array of all characters to check for
const text = "whatever you want" // text you want to check in
let flag = true // flipped to false if one character in the array not found
toCheckFor.forEach(e => {
flag &= text.includes(e)
})
Flag will be true if the text contains all characters in toCheckFor.
Here is an example based on your post ...
const mail = document.querySelector('input[name="mail"]'); // cache for later use
const warning = document.querySelector('.warning'); // cache for later use
function checkEmail() {
const error = {};
const text = mail.value;
if (!text.includes('#') && !text.includes('.')) {
warning.textContent = 'Your email address is not correct!';
return; // end here
}
/*
this is a shorthand
you can also write
if (!text.includes('#')) {
error.push('missing #');
}
*/
!text.includes('#') && error.push('missing #');
!text.includes('.') && error.push('missing .');
if (!error[0]) { // there are some errors
warning.textContent = error.join(' & ');
}
else { // no error
warning.textContent = "You are in!";
}
}
I suggest you'd better use regex check against the input email address by the following function:
function validateEmail(email) {
const re = /^(([^<>()\[\]\\.,;:\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,}))$/;
return re.test(String(email).toLowerCase());
}
I have a form that uses asp:requiredvalidator and some custom javascript to apply a red 1px border around any field that hasn't been correctly filled in.
This works perfectly, but now I want to be able to immediately remove the red border when the user correctly fills in the field.
To achieve this, I am using Jquery's focusout() method to compare the user input to a regular expression. So far I have this correctly working on every field (including email validation) except zip code. For some reason, all the validation methods I have written work perfectly except for zip code.
Here is a working email validation for example
if (id == "email1" || id == "email2") {
emailValue = e.target.value;
if (validateEmail(emailValue)) {
$("#" + id).removeClass("ErrorControl");
}
else {
}
}
function validateEmail(email) {
var re = /^(([^<>()[\]\\.,;:\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,}))$/;
return re.test(email);
}
This works perfectly and removes the red border as soon as the field losses focus and the email is valid.
But I cannot get my zip validator working, even though it works almost the exact same way.
Here is the non working zip example
//Zip code also require special validation to confirm
if (id == "zip") {
zipValue = e.target.value;
if (validateZip(zipValue)) {
$("#" + id).removeClass("ErrorControl")
}
}
//Simple zip validator
function validateZip(zip) {
var re = /^[0-9]{5}$/;
return re.test(zip);
}
Unfortunately this still removes the red border, even when I enter just letters in it! Why is this happening?
https://jsfiddle.net/hhjvstp3/
I have given both email and zip a class of ErrorControl since I cannot run asp validators on jsfiddle. This works exactly like I am describing. Email validates well, zip code removes the border no matter what.
Updated fiddle
You can see which line removes the ErrorControl class from zip
if (id == "firstname" || id == "lastname" || id == "address1" || id == "city" || id == "amount") {
//id == "zip" shouldn't be here
if (e.target.value != "") {
$("#" + id).removeClass("ErrorControl");
}
}
so i have been looking all over the internet for some simple javascript code that will let me give an alert when a field is empty and a different one when a # is not present. I keep finding regex, html and different plugins. I however need to do this in pure Javascript code. Any ideas how this could be done in a simple way?
And please, if you think this question doesn't belong here or is stupid, please point me to somewhere where i can find this information instead of insulting me. I have little to no experience with javascript.
function test(email, name) {
}
Here if you want to validate Email, use following code with given regex :
<input type="text" name="email" id="emailId" value="" >
<button onclick = "return ValidateEmail(document.getElementById('emailId').value)">Validate</button>
<script>
function ValidateEmail(inputText){
var mailformat = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/;
if(inputText.match(mailformat)) {
return true;
}
else {
alert("You have entered an invalid email address!");
return false;
}
}
</script>
Or if you want to check the empty field, use following :
if(trim(document.getElementById('emailId').value)== ""){
alert("Field is empty")
}
// For #
var textVal = document.getElementById('emailId').value
if(textVal.indexOf("#") == -1){
alert(" # doesn't exist in input value");
}
Here is the fiddle : http://jsfiddle.net/TgNC5/
You have to find an object of element you want check (textbox etc).
<input type="text" name="email" id="email" />
In JS:
if(document.getElementById("email").value == "") { // test if it is empty
alert("E-mail empty");
}
This is really basic. Using regexp you can test, if it is real e-mail, or some garbage. I recommend reading something about JS and HTML.
function test_email(field_id, field_size) {
var field_value = $('#'+field_id+'').val();
error = false;
var pattern=/^([\w-\.]+)#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;
if(!pattern.test(field_value)){
error = true;
$('#'+field_id+'').attr('class','error_email');
}
return error;
}
This will check for empty string as well as for # symbol:
if(a=="")
alert("a is empty");
else if(a.indexOf("#")<0)
alert("a does not contain #");
You can do something like this:
var input = document.getElementById('email');
input.onblur = function() {
var value = input.value
if (value == "") {
alert("empty");
}
if (value.indexOf("#") == -1) {
alert("No # symbol");
}
}
see fiddle
Although this is not a solid soltuion for checking email addresses, please see the references below for a more detailed solution:
http://www.regular-expressions.info/email.html
http://www.codeproject.com/Tips/492632/Email-Validation-in-JavaScript
---- UPDATE ----
I have been made aware that there is no IE available to target, so the input field needs to be targeted like so:
document.getElementsByTagName("input")
Using this code will select all input fields present on the page. This is not what are looking for, we want to target a specific input field. The only way to do this without a class or ID is to selected it by key, like so:
document.getElementsByTagName("input")[0]
Without seeing all of your HTML it is impossible for me to know the correct key to use so you will need to count the amount of input fields on the page and the location of which your input field exists.
1st input filed = document.getElementsByTagName("input")[0]
2nd input filed = document.getElementsByTagName("input")[1]
3rd input filed = document.getElementsByTagName("input")[2]
4th input filed = document.getElementsByTagName("input")[3]
etc...
Hope this helps.
I have the following validation on a form field:
$(".controlsphone input").blur(function() {
var ree = /^\d+$/;
if(ree.test(document.getElementById("register_telephone").value))
{
$(this).css('border-color','green');
$(this).siblings('.info').css('display','none');
$(this).siblings('.error').css('display','none');
$(this).siblings('.valid').css('display','inline-block');
$("#email_error401112").hide();
$('#registerErrors').hide();
}
else
{
$('#registerErrors').show();
$('#email_error401112').remove();
$('#registerErrors').append('<p id="email_error401112">Please enter a phone number</p>');
}
});
I would like to only validate the field if a number exists. The field is not required, but if there is content within the field, it needs to be valid (a number)
How does the above code look? Any ideas what i can do to implement this?
Cheers, Dan
Use
var ree = /^\d*$/;
because + stands for one or more, excluding zero.
while * stands for zero or more