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;
}
}
Related
I want the form to not be submitted when the inputs are wrong. The error messages do appear but my form still gets submitted nonetheless. I cant seem to find the problem would appreciate the help thank you :)-----------------------------------------------------------------------------------------------------
<form action="/handleServer.php" method="get" onsubmit="return validateForm()">
<!-- starting with first name-->
<h4 class="heading" >First name:</h4>
<input id="fname" type="text" name="fname" size="30">
<span id="errorName" class="error"></span>
<!-- module code -->
<h4 class="heading">Module code:</h4>
<input id="mcode" type="text" name="mcode" size="30">
<span id="errorCode" class="error"></span>
<input type="submit" value="Submit">
</form>
<script>
//input field using if-else statements
function validateForm() {
var fname = document.getElementById("fname").value;
var mcode = document.getElementById("mcode").value;
var errorN = document.getElementById("errorName");
var errorC = document.getElementById("errorCode");
//test for an empty input
if (fname === '' && mcode === '') {
errorN.innerHTML = "Please fill in the blank";
errorC.innerHTML = "Please fill in the blank";
return false;
}
if (fname === '') {
errorN.innerHTML = "Please fill in the blank";
return false;
} else {
errorN.innerHTML = "";
}
if (mcode === '') {
errorC.innerHTML = "Please fill in the blank";
return false;
} else {
errorC.innerHTML = "";
}
//test for invalid format
if (/^[A-Z]\D{2,30}$/.test(fname) == false) //if its true, it will go to the second input
{
errorN.innerHTML = "One capital letter and no digits allowed";
fname.style.color="red";
return false;
} else {
fname.innerHTML = "";
}
if (/^[a-z]{3}[1-9]\d{4}$/.test(mcode) == false)
{
errorC.innerHTML = "Wrong format";
mcode.style.color="red";
return false;
} else {
mcode.innerHTML = "";
}
return true; }
The problem seems to be these four lines of code:
fname.style.color="red";
fname.innerHTML = "";
mname.style.color="red";
mname.innerHTML = "";
fname and mname are strings, therfore fname.style and mname.style both result in undefined. Obviously you can't set properties on undefined which is why you are getting an error.
//You are getting the value properties which are strings:
var fname = document.getElementById("fname").value;
var mcode = document.getElementById("mcode").value;
The error is stopping your code before you can return false, preventing the cancelation of the form submit.
The solution is to instead make two more variables storing the actual input elements:
var finput = document.getElementById("fname");
var minput = document.getElementById("mname");
Then change lines:
fname.style.color="red";
fname.innerHTML = "";
mname.style.color="red";
mname.innerHTML = "";
to:
finput.style.color="red";
finput.innerHTML = "";
minput.style.color="red";
minput.innerHTML = "";
Here is a working version:
<form action="/handleServer.php" method="get" onsubmit="return validateForm()">
<!-- starting with first name-->
<h4 class="heading">First name:</h4>
<input id="fname" type="text" name="fname" size="30">
<span id="errorName" class="error"></span>
<!-- module code -->
<h4 class="heading">Module code:</h4>
<input id="mcode" type="text" name="mcode" size="30">
<span id="errorCode" class="error"></span>
<input type="submit" value="Submit">
</form>
<script>
//input field using if-else statements
function validateForm() {
var finput = document.getElementById("fname");
var minput = document.getElementById("mname");
var fname = document.getElementById("fname").value;
var mcode = document.getElementById("mcode").value;
var errorN = document.getElementById("errorName");
var errorC = document.getElementById("errorCode");
//test for an empty input
if (fname === '' && mcode === '') {
errorN.innerHTML = "Please fill in the blank";
errorC.innerHTML = "Please fill in the blank";
return false;
}
if (fname === '') {
errorN.innerHTML = "Please fill in the blank";
return false;
} else {
errorN.innerHTML = "";
}
if (mcode === '') {
errorC.innerHTML = "Please fill in the blank";
return false;
} else {
errorC.innerHTML = "";
}
//test for invalid format
if (/^[A-Z]\D{2,30}$/.test(fname) == false) //if its true, it will go to the second input
{
errorN.innerHTML = "One capital letter and no digits allowed";
finput.style.color = "red";
return false;
} else {
finput.innerHTML = "";
}
if (/^[a-z]{3}[1-9]\d{4}$/.test(mcode) == false) {
errorC.innerHTML = "Wrong format";
minput.style.color = "red";
return false;
} else {
minput.innerHTML = "";
}
return true;
}
</script>
Pass the event to the form validation function
onsubmit="return validateForm(e)"
Then prevent default submission using
e.preventDefault();
Your return statement should be inside a condition. Right now you're existing the condition and ending the function with a return true; regardless of what the conditional statements have already returned. So:
if (fname === '' && mcode === '') {
errorN.innerHTML = "Please fill in the blank";
errorC.innerHTML = "Please fill in the blank";
return false;
}else{
return true; // THIS IS WHERE YOU NEED TO RETURN TRUE
}
I see you're returning false in multiple if statements. You'll need to find a way to unify the conditions so that you have one return only for for either true or false.
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;
}
}
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.)
I am having a hard time trying to do a correct form validation. I have Name, Email, and Phone Number fields. I implemented the validation check for all of them and when I click on the submit query, it returns email as false, but not anything else. It also will still submit the form. How do I fix this?
JSFiddle: http://jsfiddle.net/GVQpL/
JavaScript Code:
function validateForm(/*fullName, email, phoneNumber*/)
{
//-------------------------NAME VALIDATION-----------------------------//
var fullNameV = document.forms["queryForm"]["fullName"].value;
if (fullNameV == null || fullNameV == "")
{
alert("Name must be filled out!");
return false;
}
else if(fullNameV.indexOf(" ") <= fullNameV.length)
{
alert("Not a valid name");
return false;
}
//-------------------------EMAIL VALIDATION-----------------------------//
var emailV = document.forms["queryForm"]["email"].value;
if (emailV == null || emailV == "")
{
alert("Email must be filled out!");
return false;
}
var atpos = emailV.indexOf("#");
var dotpos = emailV.lastIndexOf(".");
if (atpos < 1 || dotpos < atpos + 2 || dotpos + 2 >= x.length)
{
alert("Not a valid e-mail address");
return false;
}
//-------------------------PHONE # VALIDATION-----------------------------//
var phoneNumberV = document.forms["queryForm"]["phoneNumber"].value;
if (phoneNumberV == null || phoneNumberV == "")
{
alert("Phone Number must be filled out!");
return false;
}
var error = "";
var stripped = phoneNumberV.replace(/[\(\)\.\-\ ]/g, '');
if (phoneNumberV == "")
{
error = alert("You didn't enter a phone number.\n");
phoneNumberV.style.background = 'Yellow';
}
else if (isNaN(parseInt(stripped)))
{
error = alert("The phone number contains illegal characters.\n");
phoneNumberV.style.background = 'Yellow';
}
else if (!(stripped.length == 10))
{
error = alert("The phone number is the wrong length. Make sure you included an area code.\n");
phoneNumberV.style.background = 'Yellow';
}
return error;
}
Update your fiddle's html for the function to be called onsubmit="return validateForm()" and removed the required="required" changed your function to work, you can see it here:
http://jsfiddle.net/GVQpL/3/
function validateForm(/*fullName, email, phoneNumber*/)
{
//-------------------------NAME VALIDATION-----------------------------//
var fullNameV = document.forms["queryForm"]["fullName"].value;
if (fullNameV == null || fullNameV == "")
{
alert("Name must be filled out!");
document.forms["queryForm"]["fullName"].focus();
return false;
}
else if(fullNameV.indexOf(" ") >= fullNameV.length)
{
alert("Not a valid name");
document.forms["queryForm"]["fullName"].focus();
return false;
}
//-------------------------EMAIL VALIDATION-----------------------------//
var emailV = document.forms["queryForm"]["email"].value;
if (emailV == null || emailV == "")
{
alert("Email must be filled out!");
document.forms["queryForm"]["email"].focus();
return false;
}
var emailReg = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
if(!emailReg.test(emailV)){
alert("Not a valid e-mail address");
document.forms["queryForm"]["email"].focus();
return false;
}
//-------------------------PHONE # VALIDATION-----------------------------//
var phoneNumberV = document.forms["queryForm"]["phoneNumber"].value;
if (phoneNumberV == null || phoneNumberV == "")
{
alert("Phone Number must be filled out!");
document.forms["queryForm"]["phoneNumber"].focus();
return false;
}
var error = "";
var stripped = phoneNumberV.replace(/[\(\)\.\-\ ]/g, '');
if (phoneNumberV == "")
{
alert("You didn't enter a phone number.\n");
document.forms["queryForm"]["phoneNumber"].focus()
document.forms["queryForm"]["phoneNumber"].style.background = 'Yellow';
return false;
}
else if (isNaN(parseInt(stripped)))
{
alert("The phone number contains illegal characters.\n");
document.forms["queryForm"]["phoneNumber"].focus();
document.forms["queryForm"]["phoneNumber"].style.background = 'Yellow';
return false;
}
else if (!(stripped.length == 10))
{
alert("The phone number is the wrong length. Make sure you included an area code.\n");
document.forms["queryForm"]["phoneNumber"].focus();
document.forms["queryForm"]["phoneNumber"].style.background = 'Yellow';
return false;
}
if(!confirm('Are you sure you want to submit your DSLR query?')){
return false;
}
return true;
}
I have the following form:
<form name="survey1" action="add5up.php" method="post" onsubmit="return validateForm()">
<div id="question">Q1) My programme meets my expectations</div><br />
Always<INPUT TYPE = 'Radio' Name ='q1' value= 'a'>
Usually<INPUT TYPE = 'Radio' Name ='q1' value= 'b'>
Rarely<INPUT TYPE = 'Radio' Name ='q1' value= 'c'>
Never<INPUT TYPE = 'Radio' Name ='q1' value= 'd'>
<input type="submit" value="addData" />
</form>
I am trying to validate whether a Radio button has been selected.
The code I am using:
<script type="text/javascript">
function validateForm()
{
if( document.forms["survey1"]["q1"].checked)
{
return true;
}
else
{
alert('Please answer all questions');
return false;
}
}
</script>
This is not working. Any ideas?
When using radiobuttons you have to go through to check if any of them is checked, because javascript threats them as an array:
<script type="text/javascript">
function validateRadio (radios)
{
for (i = 0; i < radios.length; ++ i)
{
if (radios [i].checked) return true;
}
return false;
}
function validateForm()
{
if(validateRadio (document.forms["survey1"]["q1"]))
{
return true;
}
else
{
alert('Please answer all questions');
return false;
}
}
</script>
Regards
My solution for validation complex forms include radios.
Usage is simple, function return TRUE/FALSE after validation.
var rs_target is ID of form
scTo is my custom func to scroll to ID, you can use own function to show/scroll errors
scTo("#"+err_target);
Error box will be like
<div class="rq_message_box rq_message_box_firstname display-none">err message</div>
Validation
var validation = validateForm(rs_target);
if(validation == false){
return false;
}
Function
function validateForm(rs_target) {
var radio_arr = [];
var my_form = $("#"+rs_target);
my_form = my_form[0];
$(".rq_message_box").hide(); //clear all errors
//console.log(my_form);
var err = false;
var err_target = "";
for (key in my_form) {
//console.log("do");
if(!my_form[key]||my_form[key]==null||err){
break;
}
//console.log(my_form[key].name);
var x = my_form[key].value;
//console.log(x);
if(my_form[key].type == "radio"){
//console.log("radio");
if(radio_arr[my_form[key].name] != true){
radio_arr[my_form[key].name] = null;
}
if(my_form[key].checked){
radio_arr[my_form[key].name] = true;
}
}else{
if (x == null || x == "") {
//console.log(form[key].name.toString() + " must be filled out");
err = true;
err_target = my_form[key].name;
//return false;
}
}
}
//console.log(radio_arr);
var rad_err = false;
for (key in radio_arr) {
if(rad_err){
break;
}
var x = radio_arr[key];
if (x == null || x == "") {
//console.log("RADIO> "+key + " must be filled out");
rad_err = true;
err_target = key;
}
}
if(err || rad_err){
// some error stuff, for me show prepared error/help box with class [".rq_message_box_"+err_target] / err_target is name of input like [.rq_message_box_firsname]
$(".rq_message_box_"+err_target).show(); //show error message for input
scTo("#"+err_target); //scroll to - custom func
return false;
}else{
return true;
}
}