I need your assistant and help in modifying the below code to show the validation messages if not satisfied together not one by one. My code is:
function validateForm()
{
var x = "";
var y = "";
if ( (RFC.C1.checked) && (!RFC.Language_e.checked || !RFC.Language_e.checked ))
{
y += "Please Select the Language";
document.getElementById('error').innerHTML = y;
return false;
}
else if (document.RFC.Reason.value=="")
{
x += "Please enter a Reason";
document.getElementById('error').innerHTML = x;
return false;
}
else
{
return true;
}
}
In addition, the validation message is shown one time and if the user didn't correct it and submit the page, the error will not be shown again. Can you please help in the two issues?
I would do something like this:
function validateForm() {
var error = "";
var valid = true;
if ( (RFC.C1.checked) && (!RFC.Language_e.checked || !RFC.Language_e.checked )) {
error += "<li>Please Select the Language</li>";
valid = false;
}
else if (document.RFC.Reason.value=="") {
error += "<li>Please enter a Reason</li>";
valid = false;
}
if(valid === false) {
document.getElementById('error').innerHTML = "<ul>" + error + "</ul>";
}
return valid;
}
Get all your errors and store them.
Change the valid boolean to false if any single or multiple error occurs
Only display errors if they happen.
Link to the error locations in your page for easy navigation.
function validateForm()
{
var x = "";
var y = "";
var z = "";
if ( (RFC.C1.checked) && (!RFC.Language_e.checked || !RFC.Language_e.checked) )
{
y += "Please Select the Language";
document.getElementById('error').innerHTML = y;
return false;
}
else if ( document.RFC.Reason.value=="" )
{
x += "Please enter a Reason";
document.getElementById('error').innerHTML = x;
return false;
}
else if ( ((RFC.C1.checked) && (!RFC.Language_e.checked || !RFC.Language_e.checked )) && (document.RFC.Reason.value=="") )
{
z += "Please enter a Reason and Language";
document.getElementById('error').innerHTML = z;
return false;
}
else
{
return true;
}
}
By the way your code is working but not nice. You should read something about programming style. To get nice validation quicly you can use jQuery Validate plug-in.
Related
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 have used the following javascript code to add inline error in my form. I want to error to be removed after the error is corrected after each field is corrected. I have created a single function for all the validations, so not able to use else and remove the error manually.
var emailpattern = /^[a-zA-Z][a-zA-Z0-9_]*(\.[a-zA-Z0-9_]+)*#[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.([a-zA-Z]{2,4})$/
var passwordpattern = /^(?=.*[a-z])(?=.*[A-Z])(?=.*[$#$!%*?&])[A-Za-z\d$#$!%*?&]{8,}$/;
function validateForm() {
var x = document.forms["LoginForm"]["email"];
if (x.value == "") {
x.value = "";
document.getElementById('pointemail').innerHTML = "Please enter the email id.";
x.focus();
return false;
} else if (!emailpattern.test(x.value)) {
x.value = "";
document.getElementById('pointemail').innerHTML = "Please enter a valid email address.";
x.focus();
return false;
}
x = document.forms["LoginForm"]["password"];
if (x.value == "") {
x.value = "";
document.getElementById('pointpassword').innerHTML = "Please enter the password.";
x.focus();
return false;
} else if (!passwordpattern.test(x.value)) {
x.value = "";
document.getElementById('pointpassword').innerHTML = "Password should have minimum 8 characters, one upper case, one lower case and one special character";
x.focus();
return false;
}
}
Try This
var emailpattern = /^[a-zA-Z][a-zA-Z0-9_]*(\.[a-zA-Z0-9_]+)*#[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.([a-zA-Z]{2,4})$/
var passwordpattern = /^(?=.*[a-z])(?=.*[A-Z])(?=.*[$#$!%*?&])[A-Za-z\d$#$!%*?&]{8,}$/;
function validateForm() {
var x = document.forms["LoginForm"]["email"];
document.getElementById('pointemail').innerHTML = "";
document.getElementById('pointpassword').innerHTML = "";
//Add your if else here.
}
Hope it will be useful. :)
Provide an extra else statement after elseif
else {
document.getElementById('pointemail').innerHTML = '';
}
Similarly for pointPassword
so I have been learning basic JS and i can't get form validation to work for numbers. I will post a code snippet below. Please I am a noob so can I possibly have an answer that is easier to understand from someone who is just learning the language. The first three if statements work fine, but the fourth I have trouble with...
var checkbox = function() {
var error = "";
var firstname = document.getElementById("fn").value;
var lastname = document.getElementById("ln").value;
var email = document.getElementById("Email").value;
var age = parseInt(document.getElementById("age").value);
var address = document.getElementById("A").value;
var phone = parseInt(document.getElementById("pn").value);
if(firstname.length < 1){
error = "Enter a valid first name!";
}
if(lastname.length < 1){
error += "\nEnter a valid last name!";
}
if(email.length <1){
error += "\nEnter a valid email!";
}
if(age.length < 1 ){
error += "\nEnter a valid age!";
}
if(error.length){
alert(error)
return false;
}
return true;
}
you can try with this one
if(firstname.trim() == ""){
error = "Enter a valid first name!";
}
if(lastname.trim()==""){
error += "\nEnter a valid last name!";
}
if(email.trim() ==""){
error += "\nEnter a valid email!";
}
if(age.trim() == "" ){
error += "\nEnter a valid age!";
}
if(error.length>0){
alert(error)
return false;
}
What are you checking your age field against on? Are you checking for its presence? if so, you can do this:
if(!age) {
error += "\nThis field is required";
}
If you are checking if the value in the age field is a number, you can do this:
if(typeof age !== "number") {
error += "\nPlease enter a valid number!";
}
If you are checking if the age field is under a certain age range you can do this:
if(age !== 30) {
error += "\nYou are under 30!";
}
You should check the length of document.getElementById("age").value before call parseInt. Otherwise variable age can be NaN. For example:
var ageVal = document.getElementById("age").value;
var age;
if (ageVal){ //same as ageVal.length > 0
age = parseInt(age);
if (!age){// it can be NaN
error += "\nEnter a valid age!";
}
}
else
{
error += "\nEnter an age!"; //here we have age not set
}
Please try this
if(isNaN(age)){
error += "\nEnter a valid age!";
}
isNan() is an inbuilt javascript function. More information can be found at http://www.w3schools.com/jsref/jsref_isnan.asp
I have created a form that validates using JQuery and JavaScript. The only problem is, would be that it validates one field at a time. So the user has to correct the first field first and then press submit again to see if the next field is valid.
What I would like to to do, is have the JQuery validate the whole form after pressing submit and show all the applicable error messages.
Here is My JS:
function validateUserName()
{
var u = document.forms["NewUser"]["user"].value
var uLength = u.length;
var illegalChars = /\W/; // allow letters, numbers, and underscores
if (u == null || u == "")
{
$("#ErrorUser").text("You Left the Username field Emptyyy");
return false;
}
else if (uLength < 4 || uLength > 11)
{
$("#ErrorUser").text("The Username must be between 4 and 11 characters");
return false;
}
else if (illegalChars.test(u))
{
$("#ErrorUser").text("The Username contains illegal charectors men!");
return false;
}
else
{
return true;
}
}
function validatePassword()
{
var p = document.forms["NewUser"]["pwd"].value
var cP = document.forms["NewUser"]["confirmPwd"].value
var pLength = p.length;
if (p == null || p == "")
{
$("#ErrorPassword1").text("You left the password field empty");
return false;
}
else if (pLength < 6 || pLength > 20)
{
$("#ErrorPassword1").text("Your password must be between 6 and 20 characters in length");
return false;
}
else if (p != cP)
{
$("#ErrorPassword1").text("Th passwords do not match!");
return false;
}
else
{
return true;
}
}
function validateEmail()
{
var e = document.forms["NewUser"]["email"].value
var eLength = e.length;
var emailFilter = /^[^#]+#[^#.]+\.[^#]*\w\w$/;
var illegalChars = /[\(\)\<\>\,\;\:\\\"\[\]]/;
if (eLength == "" || eLength == null)
{
$("#ErrorEmail").text("You left the email field blank!");
return false;
}
else if (e.match(illegalChars))
{
$("#ErrorEmail").text("ILEGAL CHARECTORS DETECTED EXTERMINATE");
return false;
}
else
{
return true;
}
}
function validateFirstName()
{
var f = document.forms["NewUser"]["fName"].value;
var fLength = f.length;
var illegalChars = /\W/;
if (fLength > 20)
{
$("#ErrorFname").text("First Name has a max of 20 characters");
return false;
}
else if (illegalChars.test(f))
{
$("#ErrorFname").text("Numbers,letter and underscores in first name only");
return false;
}
else
{
return true;
}
}
function validateLastName()
{
var l = document.forms["NewUser"]["lName"].value;
var lLength = l.length;
var illegalChars = /\W/;
if (lLength > 100)
{
$("#ErrorLname").text("Last Name has a max of 100 characters");
return false;
}
else if (illegalChars.test(f))
{
$("#ErrorLname").text("Numbers,letter and underscores in last name only");
return false;
}
else
{
return true;
}
}
function validateForm()
{
valid = true;
//call username function
valid = valid && validateUserName();
//call password function
valid = valid && validatePassword();
//call email function
valid = valid && validateEmail();
//call first name function
valid = valid && validateFirstName();
//call first name function
valid = valid && validateLastName();
return valid;
}
And here is my submit form code:
$('#your-form').submit(validateForm);
Instead of returning true or false return a string containing the error and an empty string if no error was found.
Then validateForm could be something like
function validateForm()
{
error = "";
//call username function
error += "\n"+validateUserName();
//call password function
error += "\n"+validatePassword();
...
if(error === ""){
return true;
}
$("#ErrorLname").text(error);
return false;
}
Working Fiddle
var validate;
function validateUserName()
{
validate = true;
var u = document.forms["NewUser"]["user"].value
var uLength = u.length;
var illegalChars = /\W/; // allow letters, numbers, and underscores
if (u == null || u == "")
{
$("#ErrorUser").text("You Left the Username field Emptyyy");
validate = false;
}
else if (uLength <4 || uLength > 11)
{
$("#ErrorUser").text("The Username must be between 4 and 11 characters");
validate = false;
}
else if (illegalChars.test(u))
{
$("#ErrorUser").text("The Username contains illegal charectors men!");
validate = false;
}
}
function validatePassword()
{
var p = document.forms["NewUser"]["pwd"].value
var cP = document.forms["NewUser"]["confirmPwd"].value
var pLength = p.length;
if (p == null || p == "")
{
$("#ErrorPassword1").text("You left the password field empty");
validate = false;
}
else if (pLength < 6 || pLength > 20)
{
$("#ErrorPassword1").text("Your password must be between 6 and 20 characters in length");
validate = false;
}
else if (p != cP)
{
$("#ErrorPassword1").text("Th passwords do not match!");
validate = false;
}
}
function validateEmail()
{
var e = document.forms["NewUser"]["email"].value
var eLength = e.length;
var emailFilter = /^[^#]+#[^#.]+\.[^#]*\w\w$/ ;
var illegalChars= /[\(\)\<\>\,\;\:\\\"\[\]]/ ;
if (eLength == "" || eLength == null)
{
$("#ErrorEmail").text("You left the email field blank!");
validate = false;
}
else if (e.match(illegalChars))
{
$("#ErrorEmail").text("ILEGAL CHARECTORS DETECTED EXTERMINATE");
validate = false;
}
}
function validateFirstName()
{
var f = document.forms["NewUser"]["fName"].value;
var fLength = f.length;
var illegalChars = /\W/;
if(fLength > 20)
{
$("#ErrorFname").text("First Name has a max of 20 characters");
validate = false;
}
else if (illegalChars.test(f))
{
$("#ErrorFname").text("Numbers,letter and underscores in first name only");
validate = false;
}
}
function validateLastName()
{
var l = document.forms["NewUser"]["lName"].value;
var lLength = l.length;
var illegalChars = /\W/;
if(lLength > 100)
{
$("#ErrorLname").text("Last Name has a max of 100 characters");
validate = false;
}
else if (illegalChars.test(f))
{
$("#ErrorLname").text("Numbers,letter and underscores in last name only");
validate = false;
}
}
function validateForm()
{
validateUserName();
validatePassword();
validateEmail();
validateFirstName();
validateLastName();
return validate;
}
You need to access all the fields and check if the field is valid r not. If the field is valid skip it, otherwise put the field in an array. When all the fields have been checked, then display the error fields from the array all at one time.
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 = "";
}
}