Currently I have got the following code and I keep hearing that I should not use the alert function, it's old fashioned etc.
What else could I use instead of alert?
document.getElementById("practiseForm").onsubmit = function() {
if(document.getElementById("fname").value.trim() === ""){
alert("First Name Field Cannot Be Blank");
allowsubmit = false;
}
if(document.getElementById("lname").value.trim() === ""){
alert("Last Name Field Cannot Be Blank");
allowsubmit = false;
}
var email = document.getElementById('email');
var emailRegEx = /[-\w.]+#([A-z0-9][-A-z0-9]+\.)+[A-z]{2,4}/;
if (!emailRegEx.test(email.value)) {
alert("Invalid Email address");
return false;
}
}
Fiddle
I updated your fiddle to provide an example of inline error messages:
document.getElementById("practiseForm").onsubmit = function() {
var fName = document.getElementById("fname");
var fNameError = fName.nextElementSibling;
var lName = document.getElementById("lname");
var lNameError = lName.nextElementSibling;
if(fName.value.trim() === ""){
fNameError.innerHTML = "First Name Field Cannot Be Blank";
allowsubmit = false;
} else {
fNameError.innerHTML = "";
}
if(document.getElementById("lname").value.trim() === ""){
lNameError.innerHTML = "Last Name Field Cannot Be Blank";
allowsubmit = false;
} else {
lNameError.innerHTML = "";
}
var email = document.getElementById('email');
var emailError = email.nextElementSibling;
var emailRegEx = /[-\w.]+#([A-z0-9][-A-z0-9]+\.)+[A-z]{2,4}/;
if (!emailRegEx.test(email.value)) {
emailError.innerHTML = "Error in e-mail format";
return false;
} else {
emailError.innerHTML = "";
}
}
http://jsfiddle.net/Ty8AQ/10/
There are so many possiblities here, and so many examples on the web.
A possibility is creating an 'error-div' where you put all the error messages in. If you want you can style the div (color red etc etc)
HTML
<ul class="error-messages">
</ul>
JS
var li = document.createElement("li");
li.innerHTML = "Insert error message here";
document.querySelector("#ul.error-messages").appendChild(li);
CSS
.error-messages{color: red}
Another possibility are inline error messages next to the text box
Error messages when you hover on the input field
...
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 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 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
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.)
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 = "";
}
}