Email validation for specific domain not working - javascript

I have the following form
register.php
<form class="form" action="home.php" method ="POST" enctype="application/x-www-form-urlencoded">
<input type="email" name="email" placeholder="Email Address" id="email"/>
home.php
<script = "text.javasccript>
$('button').on('click', function(){
str = $('input').val();
str = str.split('#').slice(1);
var allowedDomains = [ 'correct.com' ];
if ($.inArray(str[0], allowedDomains) !== -1) {
alert(str + ' is allowed');
}else{
alert('not allowed');
}
});
</script>
I know this question has been asked before but there are no actual answers for it. Where do I integrate the following function to work with the registration form
THIS IS NEW, EDITED CODE BUT DOESNT WORK CAN ANYONE HELP?
My only output message is the one saying that the domain is not allowed even when I type the 'allowed' domain in. Here is my code:
register.php
<fieldset style = "border-radius:30px;">
<legend>Your Personal Details:</legend>
<form class="form" action="staffhome.php" method ="POST" enctype="application/x-www-form-urlencoded">
<br> <input type="text" name="forename" placeholder ="Forename" id="forename"style = "display:inline; float:left;margin-left:5%;"/>
<input type="text" name="surname" placeholder="Surname" id="surname"style = "display:inline; float:left;margin-left:5%;"/>
<input type="email" name="email" placeholder="Email Address" id="email"style = "display:inline; float:left;margin-left:5%;"/><br /><br><br><br>
<script type = "text/javascript">
$('form').on('submit', function(e){
str = $('input').val();
str = str.split('#').slice(1);
var allowedDomains = [ 'wearecallidus.com' ];
if ($.inArray(str[0], allowedDomains) !== -1) {
alert(str + ' is allowed');
}else{
alert('not allowed');
e.preventDefault();
}
});
</script>
<input type="text" name="phone" placeholder="Phone Number" id="phone"style = "display:inline;margin-right:2.5%"/>
<input type="text" name="ext" placeholder="Extension Number" id="ext"style = "display:inline;margin-left:2.5%;"/><br>
</br>
<hr style="border-top: dotted 1px;" />
<br> <input type="text" name="securityq" placeholder="Security Question" id="securityq" size ="32" maxlength ="60" style = "display:inline;"/>
<input type="text" name="securitya" placeholder="Security Answer" id="securitya" size="32"style = "display:inline;"/><br />
<br><input type="password" name="password" id="password" value="" size="32" placeholder="Type A Password" minlength="6"/><br><br>
<input type="password" name="password-check" id="password-check" value="" size="32" placeholder ="Re-Type Your Password" minlength="6"/><br>
</br>
<input id="button" type="submit" value="Register" disabled="disabled" name="submit">
</fieldset>
I get the same output message every time no matter what the input, can anyone tell me why?

I would do this if I were to have the js in the same page instead of externalising it:
<!DOCTYPE html>
<html>
<head>
<title>Form example</title>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(function() {
var allowedDomains = [ 'correct.com' ];
$('#myForm').on('submit', function(e) { // when the form is submitted
var str = $('#email').val(),
domain = str.split('#')[1]; // split on # and take the second part
if ($.inArray(domain, allowedDomains) == -1) {
alert(domain+' not allowed');
e.preventDefault(); // stop form submission
}
});
});
</script>
</head>
<body>
<div id="content">
<form id="myForm" class="form" action="home.php" method ="POST" enctype="application/x-www-form-urlencoded">
<input type="email" name="email" placeholder="Email Address" id="email"/>
<input type="submit" />
</form>
</div>
</body>
</html>
Example
$(function() {
var allowedDomains = ['correct.com'];
$('#myForm').on('submit', function(e) {
var str = $('#email').val(),
domain = str.split('#')[1];
if (!domain) domain="An empty domain"
$("#emailmsg").html("").hide()
if ($.inArray(domain, allowedDomains) == -1) {
$("#emailmsg").html(domain + ' not allowed').show();
e.preventDefault(); // stop form submission
}
});
});
#emailmsg { display:none; color:red }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="content">
<form id="myForm" class="form" action="home.php" method="POST" enctype="application/x-www-form-urlencoded">
<input type="email" name="email" placeholder="Email Address" id="email" /> <span id="emailmsg"></span><br/>
<input type="submit" />
</form>
</div>
Using your form after removing the disabled from the submit and added ID="myForm" and a span:
var allowedDomains = ['correct.com'];
function checkEmail(emailId) {
var $email=$("#"+emailId);
var str = $email.val(),domain = str.split('#')[1];
if (!domain) domain = "Empty domain";
if ($.inArray(domain, allowedDomains) == -1) {
$email.attr("placeholder", domain + ' not allowed').addClass("redborder");
}
else {
$email.attr("placeholder", "Email address").removeClass("redborder");
}
}
$(function() {
$('#myForm').on('submit', function(e) {
if (!checkEmail("email")) e.preventDefault(); // stop form submission
});
$("#email").on("keyup, blur",function() { checkEmail("email"); } );
});
.redborder {
border: 1px solid red
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<fieldset style="border-radius:30px;">
<legend>Your Personal Details:</legend>
<form id="myForm" class="form" action="staffhome.php" method="POST" enctype="application/x-www-form-urlencoded">
<br>
<input type="text" name="forename" placeholder="Forename" id="forename" style="display:inline; float:left;margin-left:5%;" />
<input type="text" name="surname" placeholder="Surname" id="surname" style="display:inline; float:left;margin-left:5%;" />
<input type="email" name="email" placeholder="Email Address" id="email" style="display:inline; float:left;margin-left:5%;" />
<br>
<br>
<br>
<br>
<input type="text" name="phone" placeholder="Phone Number" id="phone" style="display:inline;margin-right:2.5%" />
<input type="text" name="ext" placeholder="Extension Number" id="ext" style="display:inline;margin-left:2.5%;" />
<br>
</br>
<hr style="border-top: dotted 1px;" />
<br>
<input type="text" name="securityq" placeholder="Security Question" id="securityq" size="32" maxlength="60" style="display:inline;" />
<input type="text" name="securitya" placeholder="Security Answer" id="securitya" size="32" style="display:inline;" />
<br />
<br>
<input type="password" name="password" id="password" value="" size="32" placeholder="Type A Password" minlength="6" />
<br>
<br>
<input type="password" name="password-check" id="password-check" value="" size="32" placeholder="Re-Type Your Password" minlength="6" />
<br>
</br>
<input id="button" type="submit" value="Register" name="mySubmit">
</fieldset>

If you're validating with javascript, I suggest having the script in the same page as the form. Also, since its javascript, why not do it dynamically instead of having to wait for the user to submit?
$('form').on('submit', function(e){
str = $('input').val();
str = str.split('#').slice(1);
var allowedDomains = [ 'correct.com' ];
if ($.inArray(str[0], allowedDomains) !== -1) {
alert(str + ' is allowed');
}else{
alert('not allowed');
e.preventDefault();
}
});
Working fiddle:
https://jsfiddle.net/j84mqq6k/1/

Try with this using jQuery.
var email = $("#email").val();
var atpos = email.indexOf("#");
var dotpos = email.lastIndexOf(".");
if (email === null || email === "") {
alert('Please enter email address.!');
$('#email').focus();
} else if (atpos < 1 || dotpos < atpos + 2 || dotpos + 2 >= email.length) {
alert('Please enter valid email address.!');
$('#email').focus();
}

Related

How can I enable my button when 'email' field is valid? [duplicate]

This question already has answers here:
How can I validate an email address in JavaScript?
(79 answers)
Closed 1 year ago.
I did this function so that the form button enables when the inputs are different from empty, but I don't know how to do so that in the #email ID the input, in addition to being different from empty, must necessarily contain the character '"#" or the strings "# gmail.com", "# hotmail.com".
This is the function
$(function () {
$('#button').attr('disabled', true);
$('#textarea, #email, #name').change(function () {
if ($('#name').val() != '' && $('#email').val() != '' && $('#textarea').val() != '') {
$('#button').attr('disabled', false);
} else {
$('#button').attr('disabled', true);
}
});
});
This is the HTML
<form id="contact-form" method="POST" action="forms/contact-form-handler.php">
<span class="asterisco">*</span><input name="name" id="name" type="text" class="form-control" placeholder="Nombre" required>
<br>
<span class="asterisco">*</span><input name="email" id="email" type="email" class="form-control" placeholder="Dirección de correo electrónico" required>
<br>
<span class="asterisco">*</span><textarea style="resize: none;" id="textarea" name="message" class="form-control" placeholder="Mensaje" row="4" required></textarea>
<span class="texto-asterisco">Las celdas marcadas con * son obligatorias.</span>
<br>
<div id="button-container">
<button type="submit" id="button" disabled="disabled"></button>
</div>
</form>
Use a regex and test whether the value of the email input field matches it.
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,}))$/;
$(function() {
$('#button').attr('disabled', true);
$('#textarea, #email, #name').change(function() {
if ($('#name').val() != '' && re.test($('#email').val()) != '' && $('#textarea').val() != '') {
$('#button').attr('disabled', false);
} else {
$('#button').attr('disabled', true);
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="contact-form" method="POST" action="forms/contact-form-handler.php">
<span class="asterisco">*</span><input name="name" id="name" type="text" class="form-control" placeholder="Nombre" required>
<br>
<span class="asterisco">*</span><input name="email" id="email" type="email" class="form-control" placeholder="Dirección de correo electrónico" required>
<br>
<span class="asterisco">*</span><textarea style="resize: none;" id="textarea" name="message" class="form-control" placeholder="Mensaje" row="4" required></textarea>
<span class="texto-asterisco">Las celdas marcadas con * son obligatorias.</span>
<br>
<div id="button-container">
<button type="submit" id="button" disabled="disabled">Submit</button>
</div>
</form>

showing form result in popup window

how to show the result of First name and email in popup window.open.
example :
Congratulations!
Name :
EMail :
function validateForm()
{
var ufname=document.forms["regform"]["fname"].value;
var uemail=document.forms["regform"]["email"].value;
if (ufname=="" || uemail=="")
{
alert("PLEASE ENTER THE VALUES!");
return false;
}
}
<form method="post" name="regform" id="regform" onsubmit="return validateForm()">
<label>First name </label>
<input type="text" name="fname" id="fname" placeholder="Your Name">
<label>Email Address </label>
<input type="text" name="email" id="email" placeholder="hi#domain.com">
<button type="submit" value="submit">Register</button> <input type="reset" value="Reset">
</form>
If you want to do with new window try this by using window.open
function validateForm()
{
var ufname=document.forms["regform"]["fname"].value;
var uemail=document.forms["regform"]["email"].value;
if (ufname=="" || uemail=="")
{
alert("PLEASE ENTER THE VALUES!");
return false;
}
else
{
var myWindow = window.open("", "RegisterWindow", "width=200,height=100");
myWindow.document.write("<p>Congratulations! </p> <p>Name : "+ufname+".</p><p>EMail : "+ uemail +".");
}
}
<form method="post" name="regform" id="regform" onsubmit="return validateForm()">
<label>First name </label>
<input type="text" name="fname" id="fname" placeholder="Your Name">
<label>Email Address </label>
<input type="text" name="email" id="email" placeholder="hi#domain.com">
<button type="submit" value="submit">Register</button> <input type="reset" value="Reset">
</form>
try
function validateForm()
{
var ufname=document.forms["regform"]["fname"].value;
var uemail=document.forms["regform"]["email"].value;
if (ufname=="" || uemail=="")
{
alert("PLEASE ENTER THE VALUES!");
return false;
} else {
var popupWindow = window.open('');
popupWindow.document.body.innerHTML = '<div>Your Name: '+ufname+'</div><div>Your Email: '+uemail+'</div>'
}
}

form onSubmit doesn't call javascript function

I have checked recent blogs about onsubmit event not triggering the method. Those suggestions were not helpful for this problem.And i've tried this method and form in an another html page which didn't work either.So i am not able to find out where main problem is ?
My code :
<div id="_div2">
<center>
<div class="contianer">
<script type="text/javascript">
function formValidation ()
{
var fName =document.Log.firstName.value;
var lName =document.Log.lastName.value;
var pName =document.Log.penName.value;
var email =document.Log.email.value;
var password=document.Log.password.value;
var confirmPassword=document.Log.confirmPassword.value;
var status=false;
if(fName.length<1)
{
document.getElementById("firstNameLoc").innerHTML=
"<img src='Resource/unchecked.gif'/>Please Enter your First Name";
status=false;
}
else
{
document.getElementById("firstNameLoc").innerHTML=
"<img src="Resource/checked.png"/>Please Enter your First Name";
status=true;
}
return status;
}
</script>
<form name="Log" action="SignUpInsert.php" method="post" onsubmit="return formValidation();return false;">
<label><b>First Name</b></label><span id="firstNameLoc"></span><br>
<input type="text" placeholder="Enter your Last Name" name="firstName"><br>
<label><b>Last Name</b></label><span id="lastNameLoc"></span><br>
<input type="text" placeholder="Enter your Last Name" name="lastName"><br>
<label><b>Pen Name</b></label><span id="penNameLoc"></span><br>
<input type="text" placeholder="Enter your Unique Pen Name" name="penName"><br>
<label><b>Email</b></label><span id="emailLoc"></span><br>
<input type="text" placeholder="Enter your Email" name="email"><br>
<label><b>Password</b></label><span id="passwordLoc"></span><br>
<input type="password" placeholder="Enter your Password" name="password"><br>
<label><b>Confirm Password</b></label><span id="confirmPasswordLoc"></span><br>
<input type="password" placeholder="Enter your Password Again" name="confirmPassword"><br>
<input type="submit" title="Done?" value="Sign Up"><br>
<div class ="contianer">
<button type="button" class="cancelBtn" title="Go Back" onclick="location.href='Main.html'">Cancel</button>
</div>
</form>
</div>
</center>
you almost done. simple quotes problem.you could change like this in your dom else statement
document.getElementById("firstNameLoc").innerHTML = '<img src="Resource/checked.png"/>Please Enter your First Name';
function formValidation() {
var fName = document.Log.firstName.value;
var lName = document.Log.lastName.value;
var pName = document.Log.penName.value;
var email = document.Log.email.value;
var password = document.Log.password.value;
var confirmPassword = document.Log.confirmPassword.value;
var status = false;
if (fName.length < 1) {
document.getElementById("firstNameLoc").innerHTML =
"<img src='Resource/unchecked.gif'/>Please Enter your First Name";
status = false;
} else {
document.getElementById("firstNameLoc").innerHTML = '<img src="Resource/checked.png"/>Done..!';
status = true;
}
return status;
}
<div id="_div2">
<center>
<div class="contianer">
<form name="Log" action="SignUpInsert.php" method="post" onsubmit="return formValidation();return false;">
<label><b>First Name</b></label><span id="firstNameLoc"></span><br>
<input type="text" placeholder="Enter your Last Name" name="firstName"><br>
<label><b>Last Name</b></label><span id="lastNameLoc"></span><br>
<input type="text" placeholder="Enter your Last Name" name="lastName"><br>
<label><b>Pen Name</b></label><span id="penNameLoc"></span><br>
<input type="text" placeholder="Enter your Unique Pen Name" name="penName"><br>
<label><b>Email</b></label><span id="emailLoc"></span><br>
<input type="text" placeholder="Enter your Email" name="email"><br>
<label><b>Password</b></label><span id="passwordLoc"></span><br>
<input type="password" placeholder="Enter your Password" name="password"><br>
<label><b>Confirm Password</b></label><span id="confirmPasswordLoc"></span><br>
<input type="password" placeholder="Enter your Password Again" name="confirmPassword"><br>
<input type="submit" title="Done?" value="Sign Up"><br>
<div class="contianer">
<button type="button" class="cancelBtn" title="Go Back" onclick="location.href='Main.html'">Cancel</button>
</div>
</form>
</div>
</center>

Prepending only if the div isn't showing?

Basically, I want to prepend a div only if the div I'm prepending isn't already showing.
$(".loginForm").submit(function() {
var username = $("input.username").val();
var password = $("input.password").val();
var errorvisible = $("body").has(".alert.error");
if (!username || !password && errorvisible == false) {
$('body').prepend("<div class=\"error alert\">One or more field(s), have been left empty</div>");
setTimeout(function() {
$('.error.alert').fadeOut('1000', function() {
$('.error.alert').remove();
});
}, 6000);
event.preventDefault();
}
});
At the moment, I'm trying to make it so the jquery will only do the if empty if statement if the error isn't currently visible however it's not working...
<div class="pageCont">
<div class="title">
<h1>LetsChat</h1>
<h4>The new way of interaction.</h4>
</div>
<div class="login box">
<form method="POST" action="#" class="loginForm">
<input type="text" class="loginInput username" placeholder="Aquinas Email or Number" /><br>
<input type="password" class="loginInput password" placeholder="Password" /><br>
<div class="checkBox">
<input type="checkbox" id="checkBoxLink">
<label for="checkBoxLink">Remember Me</label>
Forgotten your password?
</div>
<input type="submit" value="Submit" class="login btn green" />
<input type="reset" value="Clear Fields" class="reset btn green" />
</form>
</div>
<div class="signup box">
<form method="POST" action="#" class="signupForm">
<input type="text" class="signupInput" placeholder="First Name" /><br>
<input type="text" class="signupInput" placeholder="Last Name" /><br>
<input type="text" class="signupInput" placeholder="Aquinas Email" /><br>
<input type="password" class="signupInput" placeholder="Password" /><br>
<input type="submit" class="purple btn signup" value="Sign Up Today!">
</form>
</div>
</div>
The below should work if I'm understanding your question correctly?
$(".loginForm").submit(function() {
var username = $("input.username").val();
var password = $("input.password").val();
var errorvisible = $("body").has(".alert.error").length;
if (!username || !password)
{
if(errorvisible == 0)
$('body').prepend("<div class=\"error alert\">One or more field(s), have been left empty</div>");
setTimeout(function() {
$('.error.alert').fadeOut('1000', function() {
$('.error.alert').remove();
});
}, 6000);
event.preventDefault();
}
});
I have used this type of code many times:
if(!$('#myFancyDiv').is(':visible')) {
//prepend or do whatever you want here
}
BTW just for clarity, this code checks if 'myFancyDiv' is not visible.
You can check whether the .error.alert elements exists, if so don't do anything else create a new one
$(".loginForm").submit(function() {
var username = $("input.username").val();
var password = $("input.password").val();
var errorvisible = $("body").has(".alert.error");
if (!username || !password && errorvisible == false) {
if (!$('.error.alert').length) {
$('body').prepend("<div class=\"error alert\">One or more field(s), have been left empty</div>");
setTimeout(function() {
$('.error.alert').fadeOut('1000', function() {
$(this).remove();
});
}, 6000);
}
event.preventDefault();
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form method="POST" action="#" class="loginForm">
<input type="text" class="loginInput username" placeholder="Aquinas Email or Number" />
<br>
<input type="password" class="loginInput password" placeholder="Password" />
<br>
<div class="checkBox">
<input type="checkbox" id="checkBoxLink">
<label for="checkBoxLink">Remember Me</label>
Forgotten your password?
</div>
<input type="submit" value="Submit" class="login btn green" />
<input type="reset" value="Clear Fields" class="reset btn green" />
</form>

Prevent elements from clearing after failed validation on nested .NET master page

The validation works perfectly, but if the validation fails, the form clears all data.
How can I validate the form without causing the user to have to re-enter all the data again? Due to the nature of the redirect, I need the html form to render exactly as it does now.
HTML:
<div class="formHalf">
<label for="first_name">
First Name*</label>
<input id="first_name" maxlength="40" name="first_name" size="20" type="text" class="text" />
</div>
<div class="formHalf">
<label for="last_name">
Last Name*</label>
<input id="last_name" maxlength="80" name="last_name" size="20" type="text" class="text" />
</div>
<div class="formWhole">
<label for="company">
Company</label>
<input id="company" maxlength="40" name="company" size="20" type="text" class="text" />
</div>
<div class="formWhole">
<label for="address">
Address</label>
<input id="address" maxlength="80" name="address" size="20" type="text" class="text" />
</div>
<div class="formHalf">
<label for="city">
City</label>
<input id="city" maxlength="40" name="city" size="20" type="text" class="text" />
</div>
<div class="formHalf">
<label for="state">
State/Province</label><input id="state" maxlength="20" name="state" size="20" type="text"
class="text" />
</div>
<div class="formHalf">
<label for="zip">
Zip</label><input id="zip" maxlength="20" name="zip" size="20" type="text" class="text" />
</div>
<div class="formHalf">
<label for="country">
Country</label><input id="country" maxlength="40" name="country" size="20" type="text"
class="text" />
</div>
<div class="formHalf">
<label for="email">
Email*</label><input id="email" maxlength="80" name="email" size="20" type="text"
class="text" />
</div>
<div class="formHalf">
<label for="phone">
Phone*</label><input id="phone" maxlength="40" name="phone" size="20" type="text"
class="text" />
</div>
<div class="formWhole">
<label for="description">
Description</label><textarea name="description"></textarea>
</div>
<div class="formWhole">
<input type="submit" name="formSubmit" id="formSubmit">
</div>
</div>`
SCRIPT:
<script type="text/javascript" language="javascript">
$(document).ready(function () {
$("#formSubmit").click(function () {
for (i = 0; i < 1; i++) {
var isValid = validateForm();
if (isValid) { }
$("form").attr("action", "https://www.other web site that redirects back to my page after logging form");
}
});
});
function validateForm() {
var message = "";var message2="";
var elements = new Array("first_name", "last_name", "phone", "email");
var userElement = new Array(" First Name", "Last Name", "Phone Number", "E-Mail Address");
for (i = 0; i < elements.length; i++)
{
var x = document.getElementById(elements[i]).value;
if (x == null || x == "") {
if (message != "")
message += ", "; message += userElement[i];
}
if (i == 3 && x != null && x != "") {
var atpos = x.indexOf("#");
var dotpos = x.lastIndexOf(".");
if (atpos < 1 || dotpos < atpos + 2 || dotpos + 2 >= x.length) {
message2 += "The email address is not valid.";
}
}
if (i == 2 && x != null && x != "") {
var checknumber = x.replace(/[^0-9]/g, '');
if (checknumber.length != 10 && checknumber.length != 11) {
message2 += "The phone number is needs to be in format 123-456-7890 or 1-234-567-8901.";
}
}
// email and phone validation
}
if (message != "" || message2 != "") {
if (message != "") {
message += " must be filled out.";
}
message += message2;
alert(message);
return false;
}
return true;
}
</script>`
The easiest way is just to catch the POST or GET value's on the server's side. When using PHP for example you can refill the First name by adding the following the corresponding input-tag:
value="<?=$_POST['first_name']?>"
You should change the POST tot GET if it's a get-action. Don't forget to additionally validate at the server's side.
if the extension of your page is aspx then add the runat="server" attribute to each data input tag and then you will have the data persisted !

Categories