So now I have my successful code. But what I want to do is include this in my AJAX. So this is my AJAX:
function checkEmail() {
// var myForm = $("#mainForm").serialize();
var fname = $("#first").val();
var lname = $("#second").val();
var email = $("#email").val();
var password = $("#password").val();
var repass = $("#en").val();
if (fname && lname && email && password && repass && password.length >= 6 && password == repass)) {
jQuery.ajax({
url: "connection.php",
data: {
fname:fname,
lname:lname,
email:email,
password:password,
repass:repass
},
type: "POST",
success:function(data){
$("#emailExists").show();
$("#email").css("border","2px solid green");
$("#no").css("visibility","hidden");
$("#yes").css("visibility","visible");
if(data){
$("#email").css("border", "2px solid red");
$("#no").css("visibility","visible");
$("#yes").css("visibility","hidden");
}else
{
$("#email").css("border", "2px solid green");
$("#no").css("visibility","hidden");
$("#yes").css("visibility","visible");
window.location.href = 'home.php';
}
$("#emailExists").html(data);
},
error:function (){
}
});
}
}
So, what I want to do, is basically, in that if statement [if(name && lname...)]. In that particular section, I want to include this particular checking if email valid system too. So I was thinking maybe make this code (the if statement to check if email is valid), into a function, to then add it into the AJAX, so something like this:
if (fname && lname && email && password && repass && password.length >= 6 && password == repass && checkValidateEmail()) {
But if I keep that if statement in a function called checkValiateEmail() and do that, it isn't working. What should I do?
Your error is in line 20 (of my snippet, see below). You are passing your email HTMLElement to the validateEmail() function, not the inputs value. The correct code is the following, you had validateEmail(email).
if(email.value === ""){
// ...
}
else if (!validateEmail(email.value)){ // <- the error was here
// ...
}
else{
// ...
}
The full working code is then:
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(email);
}
const email = document.getElementById("email");
const no = document.getElementById("no");
const yes = document.getElementById("yes");
const mailText = document.getElementById("email-text");
const validEmail = document.getElementById("valid");
email.addEventListener("change", function(){
if(email.value === "") {
no.style.visibility = 'visible';
yes.style.visibility = 'hidden';
email.style.border = '2px solid red';
mailText.style.visibility = 'visible';
mailText.innerText = "Please enter an email address.";
validEmail.style.visibility = 'hidden';
} else if (!validateEmail(email.value)) {
no.style.visibility = 'visible';
yes.style.visibility = 'hidden';
email.style.border = '2px solid red';
mailText.style.visibility = 'hidden';
validEmail.style.visibility = 'visible';
} else {
yes.style.visibility = 'visible';
no.style.visibility = 'hidden';
email.style.border = '2px solid green';
mailText.style.visibility = 'hidden';
}
});
<input type="text" id="email" />
<span id="yes">Yes</span>
<span id="no">No</span>
<span id="valid">Valid</span>
<p id="email-text"></p>
Related
I want to disable my submit button if all three validation rules below fails otherwise disable false. Any help
<script>
const form = document.getElementById('signup-form');
let name = document.getElementById('name');
let email = document.getElementById('email');
let password = document.getElementById('password');
let button = document.getElementById("signup-button");
form.addEventListener('keyup', (e) => {
e.preventDefault();
checkValidation();
});
function checkValidation() {
let nameValue = name.value.trim();
let emailValue = email.value.trim();
let passwordValue = password.value.trim();
let emailValidate = /^\w+#[a-zA-Z_]+?\.[a-zA-Z]{2,3}$/;
if (nameValue == "" || nameValue == null) {
document.getElementById('name-error').style.display = 'block';
document.getElementById('name-error').innerText = "Name Cannot be blank";
} else {
document.getElementById('name-error').style.display = 'none';
}
if (emailValue == "" || emailValue == null) {
document.getElementById('email-error').style.display = 'block';
document.getElementById('email-error').innerText = "Email Cannot be blank";
} else if (!emailValidate.test(emailValue)) {
document.getElementById('email-error').style.display = 'block';
document.getElementById('email-error').innerText = "Please Enter a Valid email";
} else {
document.getElementById('email-error').style.display = 'none';
}
if (passwordValue == "" || passwordValue == null) {
document.getElementById('password-error').style.display = 'block';
document.getElementById('password-error').innerText = "Password Cannot be blank";
} else {
document.getElementById('password-error').style.display = 'none';
}
}
</script>
Now I want to disable my submit button? How can it be achieved
In that function, initialize a variable, lets say isValid to true.
In the checks, if any check fails, set isValid to false.
And at the bottom of the function, add a condition to enable or disable the Submit button. I'm providing a sample code for your reference.
if (isValid === true) {
// Enable the submit button
}
else {
// Enable the submit button
}
You can add a flag like this:
<script>
const form = document.getElementById('signup-form');
let name = document.getElementById('name');
let email = document.getElementById('email');
let password = document.getElementById('password');
let button = document.getElementById("signup-button");
let error = false;
form.addEventListener('keyup', (e) => {
e.preventDefault();
checkValidation();
});
if(error){
button.setAttribute('disabled', '')
}else{
button.removeAttribute('disabled')
}
function checkValidation() {
let nameValue = name.value.trim();
let emailValue = email.value.trim();
let passwordValue = password.value.trim();
let emailValidate = /^\w+#[a-zA-Z_]+?\.[a-zA-Z]{2,3}$/;
if (nameValue == "" || nameValue == null) {
document.getElementById('name-error').style.display = 'block';
document.getElementById('name-error').innerText = "Name Cannot be blank";
error = true;
} else {
document.getElementById('name-error').style.display = 'none';
}
if (emailValue == "" || emailValue == null) {
document.getElementById('email-error').style.display = 'block';
document.getElementById('email-error').innerText = "Email Cannot be blank";
error = true;
} else if (!emailValidate.test(emailValue)) {
document.getElementById('email-error').style.display = 'block';
document.getElementById('email-error').innerText = "Please Enter a Valid email";
} else {
document.getElementById('email-error').style.display = 'none';
}
if (passwordValue == "" || passwordValue == null) {
document.getElementById('password-error').style.display = 'block';
document.getElementById('password-error').innerText = "Password Cannot be blank";
error = true;
} else {
document.getElementById('password-error').style.display = 'none';
}
}
</script>
I've been trying to validate USA and Canadian postal codes as I'm sending them through an api. However, I can't seem to get the regex to work. My validation is a bit messy but it should work nonetheless, I believe the regex is correct I just have the wrong logic? I would appreciate any help. Thanks.
function checkoutv2() {
var typepostal;
if (xcountry == 1) {
//canada
typepostal = "Canada";
} else if (xcountry == 2) {
//usa
var typepostal = "USA";
}
console.log(xcountry);
var xfirstname = document.getElementById("firstname").value;
var xlastname = document.getElementById("lastname").value;
var xemail = document.getElementById("email").value;
var xcity = document.getElementById("city").value;
var xaddress = document.getElementById("address").value;
var xpostal = document.getElementById("postal").value;
xpostal = xpostal.toString().trim();
var reg = /^([A-Za-z0-9_\-\.])+\#([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
var ca = new RegExp(/([ABCEGHJKLMNPRSTVXY]\d)([ABCEGHJKLMNPRSTVWXYZ]\d){2}/i);
var us = new RegExp("^\\d{5}(-{0,1}\\d{4})?$");
if (xfirstname == "" || xfirstname.length > 50) {
document.getElementById("firstname").style.border = "1px solid red";
} else if (xlastname == "" || xlastname.length > 50) {
document.getElementById("lastname").style.border = "1px solid red";
} else if (reg.test(xemail) == false || xemail.lenth > 100) {
document.getElementById("email").style.border = "1px solid red";
} else if (xcity == "" || xcity.length > 100) {
document.getElementById("city").style.border = "1px solid red";
} else if (xaddress == "" || xaddress.length > 100) {
document.getElementById("address").style.border = "1px solid red";
} else if (
typepostal == "Canada" &&
ca.test(xpostal.toString().replace(/\W+/g, "")) == false &&
xpostal.length >= 10
) {
console.log("postal is cad");
console.log(xpostal);
document.getElementById("postal").style.border = "1px solid red";
} else if (
typepostal == "USA" &&
xpostal.length > 10 &&
us.test(xpostal.toString()) == false
) {
console.log("postal is us");
document.getElementById("postal").style.border = "1px solid red";
} else {
checkout();
}
}
when email are already existed, validation is hit the form action redirect the
page.i wanted to if email and all field are right way then hit the action part.
ajax success function not to return properly.
<script language="javascript">
function validate()
{
var str = true;
document.getElementById("msg1").innerHTML = "";
document.getElementById("msg2").innerHTML = "";
document.getElementById("msg3").innerHTML = "";
document.getElementById("msg4").innerHTML = "";
document.getElementById("msg5").innerHTML = "";
document.getElementById("msg6").innerHTML = "";
document.getElementById("msg7").innerHTML = "";
document.getElementById("msg8").innerHTML = "";
document.getElementById("msg9").innerHTML = "";
document.getElementById("msg10").innerHTML = "";
document.getElementById("msg11").innerHTML = "";
if (!document.frm.firstname.value == '')
{
var patterns = /^[a-zA-Z\s]*$/;
if (!document.frm.firstname.value.match(patterns))
{
document.getElementById("msg1").innerHTML = "Please Enter only letters";
str = false;
}
} else
{
document.getElementById("msg1").innerHTML = "Please Enter First Name";
str = false;
}
if (!document.frm.lastname.value == '')
{
var patterns = /^[a-zA-Z\s]*$/;
if (!document.frm.lastname.value.match(patterns))
{
document.getElementById("msg2").innerHTML = "Please Enter only letters";
str = false;
}
} else
{
document.getElementById("msg2").innerHTML = "Please Enter Last Name";
str = false;
}
if (document.frm.password.value == '')
{
document.getElementById("msg4").innerHTML = "Please Enter Password";
str = false;
}
var phoneno = /^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$/;
if (!document.frm.phone.value.match(phoneno))
{
document.getElementById("msg5").innerHTML = "Please Enter 10 Digits Mobiles";
str = false;
}
if (document.frm.country.value == '')
{
document.getElementById("msg6").innerHTML = "Please Enter Country";
str = false;
}
if (document.frm.state.value == '')
{
document.getElementById("msg7").innerHTML = "Please Enter State";
str = false;
}
if (document.frm.city.value == '')
{
document.getElementById("msg8").innerHTML = "Please Enter City";
str = false;
}
if (document.frm.address.value == '')
{
document.getElementById("msg9").innerHTML = "Please Enter Address";
str = false;
}
if (document.frm.industry.value == '')
{
document.getElementById("msg10").innerHTML = "Please Select Industry";
str = false;
}
if (document.frm.company.value == '')
{
document.getElementById("msg11").innerHTML = "Please Enter Company Name";
str = false;
}
if (!document.frm.email.value == '')
{
var validate_char = /^([a-zA-Z])+([a-zA-Z0-9_.+-])+\#(([a-zA-Z])+\.+?(com|co|in|org|net|edu|info|gov|vekomy))\.?(com|co|in|org|net|edu|info|gov)?$/;
if (!document.frm.email.value.match(validate_char))
{
document.getElementById("msg3").innerHTML = "Please Enter Valid Email ID";
str = false;
} else {
var Email = document.frm.email.value;
var datastring = 'Email=' + Email;
$.ajax({
type: "POST",
url: "client_email.php",
data: datastring,
success: function(responseText) {
if (responseText == 1)
{
$("#msg3").html("Email Is Already Exists");
str = false;
}
}
});
}
} else
{
document.getElementById("msg3").innerHTML = "Email Field Is Empty";
str = false;
}
return str;
}
</script>
Use HTML5's new type attributes to accomplish this..
For email validity write:
<input type="email" name="email" required/>
and if the email is empty or wrong manner ,it will never hit submit event..Hence will not be redirected...
For eg:https://www.w3schools.com/code/tryit.asp?filename=FNZQV8G6AJ8P
for more types:https://www.w3schools.com/html/html_form_input_types.asp
Server Side:
Form Required Every Field By PHP
Form Type Validation By PHP
I have a form with inputs
Fist name
Last name
Password
Etc
Current my validation works one by one. I would like to integrate them into one pop up box.
Example currently:
All not filled up; upon submission it would pop up First name not filled. I want it to be First name not filled, last name not filled etc
function validateForm() {
var x = document.forms["myForm"]["firstname"].value;
if (x == null || x == "") {
alert("First Name must be filled out");
return false;
}
var x = document.forms["myForm"]["lastname"].value;
if (x == null || x == "") {
alert("Last Name must be filled out");
return false;
}
var status = false;
var emailRegEx = /^[A-Z0-9._%+-]+#[A-Z0-9.-]+\.[A-Z]{2,4}$/i;
if (document.forms["myForm"]["email"].value.search(emailRegEx) == -1) {
alert("Please enter a valid email address.");
return false;
}
var status = false;
var paswordregex = /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{8,}$/;
if (document.forms["myForm"]["password"].value.search(paswordregex) == -1) {
alert("Please enter a at least 8 alphanumeric characters");
return false;
}
var password = document.getElementById("password").value;
var confirmPassword = document.getElementById("confirmpassword").value;
if (password != confirmPassword) {
alert("Passwords do not match.");
return false;
}
var checkb = document.getElementById('checkboxid');
if (checkb.checked != true) {
alert('Agree to privacy agreement must be checked');
} else {
status = true;
}
return status;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script>
function validateForm() {
var regexEmail = /^([\w-]+(?:\.[\w-]+)*)#((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
var regexMinThree = /^[A-Za-z0-9_ ]{3,13}$/;
var userFirstName = $.trim($('.firstName').val());
var userLastName = $.trim($('.lastName').val());
var userEmail = $.trim($('.email').val());
var userPassword = $.trim($('.password').val());
var msg = '';
if(!regexMinThree.test(userFirstName)) {
msg = 'FirstName, ';
} else {
msg = '';
}
if(!regexMinThree.test(userLastName)) {
msg = msg+'LastName, ';
} else {
msg = msg+'';
}
if(!regexEmail.test(userEmail)) {
msg = msg+'Email, ';
} else {
msg = msg+'';
}
if(!regexMinThree.test(userPassword)) {
msg = msg+'Password, ';
} else {
msg = msg+'';
}
if(!regexMinThree.test(userPassword) || !regexEmail.test(userEmail) || !regexMinThree.test(userLastName) || !regexMinThree.test(userFirstName)) {
msg = msg+'not filled correctly.';
alert(msg);
}
}
</script>
<form class="userRegistrationForm" onsubmit="return false;" method="post">
<input type="text" class="firstName" placeholder ="FirstName"/>
<input type="text" class="lastName" placeholder ="LastName"/>
<input type="email" class="email" placeholder ="Email"/>
<input type="password" class="password" placeholder ="Password"/>
<button type="submit" onclick="validateForm()" class="userRegistration">Submit</button>
</form>
Add a flag called error and a string called errorMessage, then in each if statement, if there is an error, make error = true and append error message.
Then when submitted, if error == true, alert errorMessage
You can add an <ul> in your html form where you want to show errors
Example
<ul class="errorContainer"></ul>
Then JS
function validateForm() {
var errors = "";
var x = document.forms["myForm"]["firstname"].value;
if (x == null || x == "") {
errors +="<li>First Name must be filled out</li>";
}
var x = document.forms["myForm"]["lastname"].value;
if (x == null || x == "") {
errors +="<li>Last Name must be filled out</li>";
}
var status = false;
var emailRegEx = /^[A-Z0-9._%+-]+#[A-Z0-9.-]+\.[A-Z]{2,4}$/i;
if (document.forms["myForm"]["email"].value.search(emailRegEx) == -1) {
errors +="<li>Please enter a valid email address.</li>";
}
var status = false;
var paswordregex = /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{8,}$/;
if (document.forms["myForm"]["password"].value.search(paswordregex) == -1) {
errors +="<li>Please enter a at least 8 alphanumeric characters</li>";
}
var password = document.getElementById("password").value;
var confirmPassword = document.getElementById("confirmpassword").value;
if (password != confirmPassword) {
errors +="<li>Passwords do not match.</li>";
}
var checkb = document.getElementById('checkboxid');
if (checkb.checked != true) {
errors +="<li>Agree to privacy agreement must be checked</li>";
}
if(errors!="")
{
$(".errorContainer").html(errors);
return false;
} else {
status = true;
return status;
}
}
I want to validate my form, if any of the input field is blank, the error warning will show beside the blank input field. The error message must be comes out all at one time for the blank input, not show one by one. How to do this?
Below is my javascript code :
function doValidate()
{
var x=document.forms["form"]["fullname"].value;
if (x==null || x=="")
{
document.getElementById('error1').innerHTML="Full name is required!";
return false;
}
var y=document.forms["form"]["uid"].value;
if (y==null || y=="")
{
document.getElementById('error2').innerHTML="Username is required!";
return false;
}
var z=document.forms["form"]["pwd"].value;
if (z==null || z=="")
{
document.getElementById('error3').innerHTML="Password is required!";
return false;
}
var a=document.forms["form"]["pwd2"].value;
if (a==null || a=="")
{
document.getElementById('error4').innerHTML="Please re-enter your password!";
return false;
}
var pwd = document.getElementById("pwd").value;
var pwd2 = document.getElementById("pwd2").value;
if(pwd != pwd2){
alert('Wrong confirm password!');
return false;
}
var b=document.forms["form"]["role"].value;
if (b==null || b=="Please select...")
{
document.getElementById('error5').innerHTML="Please select user role!";
return false;
}
}
You should start your function with var ok = true, and in each if-block, instead of having return false, you should set ok = false. At the end, return ok.
Here's what that might look like:
function doValidate() {
var ok = true;
var form = document.forms.form;
var fullname = form.fullname.value;
if (fullname == null || fullname == "") {
document.getElementById('error1').innerHTML = "Full name is required!";
ok = false;
}
var uid = form.uid.value;
if (uid == null || uid == "") {
document.getElementById('error2').innerHTML = "Username is required!";
ok = false;
}
var pwd = form.pwd.value;
if (pwd == null || pwd == "") {
document.getElementById('error3').innerHTML = "Password is required!";
ok = false;
}
var pwd2 = form.pwd2.value;
if (pwd2 == null || pwd2 == "") {
document.getElementById('error4').innerHTML = "Please re-enter your password!";
ok = false;
} else if (pwd != pwd2) {
document.getElementById('error4').innerHTML = "Wrong confirm password!";
ok = false;
}
var role = form.role.value;
if (role == null || role == "Please select...") {
document.getElementById('error5').innerHTML = "Please select user role!";
ok = false;
}
return ok;
}
(I've taken the liberty of changing to a more consistent formatting style, improving some variable-names, simplifying some access patterns, and replacing an alert with an inline error message like the others.)