javascript validation with email check - javascript

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

Related

Having trouble with the javascript file does not respond to html form

I'm trying to make a javascript file to check the rules of a registration form but the alert does not pop up so I don't know which part is not working.
When I click the submit button, It goes straight to the PHP file instead of listing messages in an alert window.
function validate() {
var name = document.getElementById("name").value;
var username = document.getElementById("username").value;
var password = document.getElementById("password").value;
var confirmPassword = document.getElementById("confirm-password").value;
var genderM = document.getElementById("gender-male").checked; //radio
var genderF = document.getElementById("gender-female").checked; //radio
var temperature = document.getElementById("temperature").checked; //checkbox
var favourite = document.getElementById("favourite").checked; //select
var email = document.getElementById("email").value;
var errMsg = "";
var result = true;
if (name == "") {
errMsg += "Please enter a name.\n";
}
if (username == "") {
errMsg += "Please enter a username.\n";
}
if (password == "") {
errMsg += "Please enter a password.\n";
}
if (confirmPassword == "") {
errMsg += "Please re-enter password.\n";
}
if (password != confirmPassword) {
errMsg += "Confirm password does not match.\n";
}
if (email == "") {
errMsg += "Please enter an email address.\n";
}
if (email.indexof('#') == 0) {
errMsg += "Email address invalid.\n";
}
if (email.indexof('#') < 0) {
errMsg += "Email address must contain an # symbol.\n";
}
if ((genderM = "" )&&(genderF = "")) {
errMsg += "Please enter a gender.\n";
}
if (temperature == "") {
errMsg += "Please enter a drink temperature.\n";
}
if (favourite == "") {
errMsg += "Please enter a favourite drink.\n";
}
if (errMsg != "") {
alert (errMsg);
result = false;
}
return result;
}
function init() {
var register = document.getElementById("register"); //form id="register"
register.onsubmit = validate;
}
window.onload = init();
I tried to double check all the posibilities error like missing ";" or wrong elements, etc. However, not thing seems to work for me.
try this
window.onload = init // assign function instead of calling it

JavaScript display multiple error message form submission?

What am I doing wrong in my JavaScript? I would like to display an error message if a user forgets to type in any of my HTML form fields. I would like to create an error message for the name, email, and phone number fields. Even if a user puts in their name, I would like error messages for the remainder 2, or remainder 1, or no error messages. I have attached my JavaScript code below. Thank you for those who help.
function validateForm() {
var ret = true;
var name = document.forms["contactform"]["name"].value;
if (name == "") {
document.getElementById('error').innerHTML = "Please enter your name";
ret = false;
}
var email = document.forms["contactform"]["email"].value;
if (email == "") {
document.getElementById('erroremail').innerHTML = "Please enter your email";
ret = false;
}
var phone = document.forms["contactform"]["phone"].value;
if (phone == "") {
document.getElementById('errorphone').innerHTML = "Please enter your phone";
ret = false;
}
return ret;
}
If you want separate error display for each input you could just add else with empty innerHTML.
Something like this:
var name = document.forms["contactform"]["name"].value;
var nameError = document.getElementById('error');
if (name == "") {
nameError.innerHTML = "Please enter your name";
ret = false;
} else {
nameError.innerHTML = "";
}
Full example here: https://jsfiddle.net/1h1tkh7y/
Create a variable called something like :
var fieldsInError = "";
Then in your validation in each check if it fails validation add the field:
fieldsInError += "name," (or whatever the field is)
Then at the end of the function update your error field with something like:
document.getElementById('error').innerHTML = "Please enter " + fieldsInError.substring(0, fieldsInError.length-1);
So your function would look something like this:
function validateForm() {
var fieldsInError = "";
var name = document.forms["contactform"]["name"].value;
if (name == "") {
fieldsInError += "name,"
}
var email = document.forms["contactform"]["email"].value;
if (email == "") {
fieldsInError += "email,"
}
var phone = document.forms["contactform"]["phone"].value;
if (phone == "") {
fieldsInError += "phone,"
}
if(fieldsInError != ""){
document.getElementById('error').innerHTML = "Please enter " + fieldsInError.substring(0, fieldsInError.length-1);
return false;
} else {
return true;
}
}

JavaScript validation form integratation into one

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;
}
}

Regex not firing on user form

My Regex for email does not seem to be working, it does not fire,
the validation on the form passes even if the user only inputs a single .
here is my code:
var a = ["txtTitle", "txtSurname", "txtEmail", "txtPostCode"];
$.each(a, function (index, value) {
if (sMsg == "") {
if ($("#" + value).val().trim() == "") {
var sText = $('td:first', $($("#" + value)).parents('tr')).text();
sMsg = "Please enter a " + sText;
$("#" + value).focus();
}
}
});
if (sMsg == "") {
if ($("#txtPhone").val().trim() == "" && $("#txtMobile").val().trim() == "") {
sMsg = "Please enter a phone or mobile number";
$("#txtPhone").focus();
}
}
if (sMsg == "") {
var regex = /^([a-zA-Z0-9_.+-])+\#(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/;
if (!regex.test($("#txtEmail").val())) {
sMsg = "Please enter a valid email address";
}
}
break;
i have now resolved this, turns out there was a primary validation on the email field to check whether it contains a value, i simply removed this and it worked
amended this line:
var a = ["txtTitle", "txtSurname", "txtEmail", "txtPostCode"];
to
var a = ["txtTitle", "txtSurname","txtPostCode"];

innerHTML is not hiding in javascript validation

function editvalidation() {
var isDataValid = true;
var currentCourseO = document.getElementById("currentCourseNo");
var newCourseNoO = document.getElementById("newCourseNo");
var currentCourseMsgO = document.getElementById("currentAlert");
var newCourseMsgO = document.getElementById("newAlert");
if (currentCourseO.value == "") {
currentCourseMsgO.innerHTML = "Please Select a Course to edit from the Course Drop Down Menu";
newCourseMsgO.innerHTML = "";
isDataValid = false;
} else {
currentCourseMsgO.innerHTML = "";
}
if (newCourseNoO.value == "") {
newCourseMsgO.innerHTML = "Please fill in the Course ID in your Edit";
isDataValid = false;
} else {
newCourseMsgO.innerHTML = "";
}
return isDataValid;
}
Hi, in the code above what I am trying to do is that if the currentCourseO.value == "" is met, then display its string message but do not display the string message for newCourseMsgO.
If currentCourseO.value == "" is not met then display the string for newCourseMsgO which is newCourseMsgO.innerHTML = "Please fill in the Course ID in your Edit"; if this validation is met.
At the moment it is not hiding the string for newCourseMsgO when currentCourseO.value == "" is met. Can I please have answer in javascript please.
It sounds like your two if-else statements should be connected, right now they are not dependent on one another. Try this:
if (currentCourseO.value == "") {
currentCourseMsgO.innerHTML = "Please Select a Course to edit from the Course Drop Down Menu";
newCourseMsgO.innerHTML = "";
isDataValid = false;
} else {
if (newCourseNoO.value == "") {
newCourseMsgO.innerHTML = "Please fill in the Course ID in your Edit";
isDataValid = false;
} else{
newCourseMsgO.innerHTML = "";
}
}

Categories