validate javascript expressions - javascript

I have done a test for a gender expression -
function gender()
{
var gender = document.form1.radio[0].checked;
var gender1 = document.form1.radio[1].checked;
if(gender || gender1)
{
}
else
{
errorMsg = errorMsg + "please select your gender\n"
}
}
but I would like to be able to write it so that there is no need for an empty positive outcome like this -
if ((alphabetic.test(fname)== false) || (alphabetic.test(lname)== false))
{
alertmsg = alertmsg + "Name should be in alphabets:" + "\n";
}
I am sorry if I appear to be very stupid, I am a complete beginner. any help would be appreciated, thanks

function gender()
{
var gender = document.form1.radio[0].checked;
var gender1 = document.form1.radio[1].checked;
if(!(gender || gender1))
{
errorMsg = errorMsg + "please select your gender\n"
}
}

If I understand correctly:
if(!gender && !gender1) {
errorMsg = errorMsg + "please select your gender\n"
}

Not really sure what you are trying to do but, try using the logical NOT "!":
function gender()
{
var gender = document.form1.radio[0].checked;
var gender1 = document.form1.radio[1].checked;
if !(gender || gender1)
{
errorMsg = errorMsg + "please select your gender\n"
}
}

Related

Why am I getting this unexpected string error?

I'm learning css + js + html rn and while making a simple pop-up message script, i started getting an unexpected string error in the following script:
function myFunction() {
var xbg = prompt("Please enter your name!", "Henry Phillips");
if (person === null || person == "")
{
txt= "Enter your name in the field.";
} else {
txt "Hello" + xbg + "! How are you today?"
}
document.getElementById("demo").innerHTML = txt;
}
As console says, the string error is specifically located here:
line
There is some errors in your script.
First you forget the = in the else statment.
txt = "Hello " + xbg + "! How are you today?"
----^
The if condition don't test the good variable name, you can replace person by xbg.
if (xbg === null || xbg == "")
// or shorter
if (xbg && xbg.trim())
And finally, you don't call your script another time if user don't enter this name. You can use setTimeout to give some time to the user for read the message before open prompt another time.
setTimeout(myFunction, 500);
See complete fixed code below
function myFunction() {
var xbg = prompt("Please enter your name!", "");
if (xbg === null || xbg == "")
{
txt = "Enter your name in the field.";
setTimeout(myFunction, 500);
} else {
txt= "Hello " + xbg + "! How are you today?"
}
document.getElementById("demo").innerHTML = txt;
}
myFunction();
<span id="demo"></span>
function myFunction() {
var person = prompt("Please enter your name!", "Put Your Name");
if (person.trim()) {
txt = "Hello, " + person + "! How are you today?"
} else {
txt = "Enter your name in the field.";
}
document.getElementById("demo").innerHTML = txt;
}
myFunction();
<div id="demo"></div>
You can find the edited script here.
so basically you have a typo here: change person with xbg
function myFunction() {
var xbg = prompt("Please enter your name!", "Henry Phillips");
if (xbg === null || xbg == "")
{
txt= "Enter your name in the field.";
} else {
txt ="Hello" + xbg + "! How are you today?"
}
document.getElementById("demo").innerHTML = txt;
}

Javascript For Loop Not Appending into Div as Expected?

Im not really sure what Im doing wrong here. I essentially check if any of the elements values are empty, and if they are it started to iterate through them.
Once it iterates it appends the id's of the elements that are empty into the div. Or at least thats what I expected it to do. Any help? Thanks!
<script>
function validate(){
var username = document.getElementById("username");
var name = document.getElementById("name");
var phone = document.getElementById("phone-number");
var email = document.getElementById("email");
var password = document.getElementById("password");
var passwordc = document.getElementById("password-confirmation");
var array = [username, name, phone, email, password, passwordc];
if(username.value == "" || name.value == "" || phone.value == "" || email.value == "" || password.value == "" || passwordc.value == ""){
document.getElementById('required-field-error').innerHTML = "The following must not be blank: ";
for(i = 0; i < array.length; i++);{
if(array[i].value == ""){
document.getElementById('required-field-error').innerHTML += " array[i].id ";
}
else{document.getElementById('required-field-error').innerHTML += "";}
}
}
else{
document.getElementById('required-field-error').innerHTML = "";
}
}
</script>
You terminated the for loop independently and hence you are getting out of bond index. And also as pointer by 'Xufox' that is literal string.
Find the corrected script below:
<script>
function validate(){
var username = document.getElementById("username");
var name = document.getElementById("name");
var phone = document.getElementById("phone-number");
var email = document.getElementById("email");
var password = document.getElementById("password");
var passwordc = document.getElementById("password-confirmation");
var array = [username, name, phone, email, password, passwordc];
if(username.value == "" || name.value == "" || phone.value == "" || email.value == "" || password.value == "" || passwordc.value == ""){
document.getElementById('required-field-error').innerHTML = "The following must not be blank: ";
for(i = 0; i < array.length; i++){
if(array[i].value == ""){
document.getElementById('required-field-error').innerHTML += " " + array[i].id;
}
else{document.getElementById('required-field-error').innerHTML += "";}
}
}
else{
document.getElementById('required-field-error').innerHTML = "";
}
}
</script>
You can greatly simplify your code by doing something like this instead:
function validate() {
const requiredFields = ['username', 'name', 'phone-number', 'email', 'password', 'password-confirmation'];
const missingFields = requiredFields.filter(requiredFieldStr => {
return !document.getElementById(requiredFieldStr).value;
});
const requiredFieldError = document.getElementById('required-field-error');
if (missingFields.length > 0) {
requiredFieldError.textContent =
"The following must not be blank: " + missingFields.join('');
} else requiredFieldError.textContent = '';
}
I don't know your requirement exactly.
But if you use JQuery validation that will simplify the things for you.

Validating using JavaScript - how to show to all validation error message's

I have function that checks if fields are blank but if all fields are blank it only shows one of the validation message's, I think this is because I have used an if statement:
function validateForm()
{
var sName=document.forms["myForm"]["surname_5"].value;
if (sName==null || sName=="")
{
document.getElementById("sNameMessage").innerHTML = "*Surname is required";
return false;
}
var x=document.forms["myForm"]["firstname_4"].value;
if (x==null || x=="")
{
document.getElementById("fNameMessage").innerHTML = "*First name is required";
return false;
}
var y=document.forms["myForm"]["selectid"];
if(y.options[y.selectedIndex].value == "Title")
{
document.getElementById("titleMessage").innerHTML = "You need to select a title";
return false;
}
}
How do I get it so all validation messages show if the user has left all fields blank?
Don't return false immediately. Set a variable to false (after defining it as true at the very start of the function) and return that variable at the end.
Try something like this (or add all your code if you need more details)
JavaScript:
function validateForm() {
var sName = document.forms["myForm"]["surname_5"].value;
var ret = true;
if (sName == null || sName == "") {
document.getElementById("sNameMessage").innerHTML = "*Surname is required";
ret = false;
}
var x = document.forms["myForm"]["firstname_4"].value;
if (x == null || x == "") {
document.getElementById("fNameMessage").innerHTML = "*First name is required";
ret = false;
}
var y = document.forms["myForm"]["selectid"];
if (y.options[y.selectedIndex].value == "Title") {
document.getElementById("titleMessage").innerHTML = "You need to select a title";
ret = false;
}
return ret;
}

alert those textboxes who is still empty

function checkvalue() {
var areaDesc = document.getElementById('areaDesc').value;
var cboLeaveType = document.getElementById('cboLeaveType').value;
var fromDate = document.getElementById('fromDate').value;
var toDate = document.getElementById('toDate').value;
if (areaDesc == "" || fromDate == "" || toDate == "" || cboLeaveType = "")
{
alert("empty hoys");
}
else
{
document.getElementById('hdnAction').value = "go";
document.frmLeave.submit();
}
}
thats the code, it is working but, I want to alert those area who is still empty,
for example.
ex1: areaDesc, fromDate, toDate is not empty, it must alert "txtSignOff still empty";
ex2: areaDesc, fromDate is not empty it must alert "toDate,txtSignOff still empty";
or
toDate is empty
toDate is empty
You can use for in like this:
function checkvalue() {
var fields = {
'areaDesc' : document.getElementById('areaDesc').value;
'cboLeaveType' : document.getElementById('cboLeaveType').value;
'fromDate' : document.getElementById('fromDate').value;
'toDate' : document.getElementById('toDate').value;
};
for(var fieldName in fields){
if(fields[fieldName] == ""){
alert("field" + fieldName + "is empty");
return false;
}
}
document.getElementById('hdnAction').value = "go";
document.frmLeave.submit();
}
You may have to split your if block into individual ones, then use a String and concatenate it with the empty field's name in each if. That is,
var emptyStr = ''
if (areaDesc == '') { emptyStr += 'areaDesc,' ; }
if (fromDate == '') { emptyStr += 'fromDate,' ; }...
...
emptyStr += ' still empty'
if (emptyStr != '') { alert(emptyStr); }
You would have to have an individual if statement for each input type you're requiring, otherwise it's a very generic error message. Something like this should do it:
Also, where is txtSignOff defined? Did you mean cboLeaveType?
If you don't want multiple alerts, just combine all the alerts from the code below and convert them into a string, and then if (error), alert the error string.
function checkvalue() {
var areaDesc = document.getElementById('areaDesc').value;
var cboLeaveType = document.getElementById('cboLeaveType').value;
var fromDate = document.getElementById('fromDate').value;
var toDate = document.getElementById('toDate').value;
if (!areaDesc) alert("areaDesc still empty");
if (!fromDate) alert("fromDate still empty");
if (!toDate) alert("toDate still empty");
if (!txtSignOff) alert("txtSignOff still empty");
if (areaDesc && fromDate && toDate && txtSignOff)
{
document.getElementById('hdnAction').value = "go";
document.frmLeave.submit();
}
}

Javascript form validator function not working properly

I have been trying to make this function work for two hours now, but am not able to find where the error is.
This is behaving unexpectedly.
When any of the field in the form is filled, the form is posted to php file,
and shows errors (as expected) only when all fields are left empty, i.e.the 5 errors.
But when any of the 6 fields is filled, the form is posted irrespective of other errors in the form.
Please help me validating this form.
error is the information of errors I will show to users.
errors is number of errors found.
JavaScript function
function formValidator(){
var elementValue = document.getElementById("first-name").value;
var elementName = document.getElementById("first-name");
var errors = 0;
var error = " ";
if (elementValue == "" || elementValue == " " || elementValue== NULL){
error = "First Name shouldn't be left empty.";
errors = 1;
}
var elementValue = document.getElementById("last-name").value;
var elementName = document.getElementById("last-name");
if (elementValue == "" || elementValue == " " || elementValue== NULL){
if (errors == 0){
error = "Last Name shouldn't be left empty.";
}
else{
error += "<br>Last Name shouldn't be left empty.";
}
errors+=1;
}
var elementValue = document.getElementById("email-for-registration").value;
var elementName = document.getElementById("email-for-registration");
var email_err = "false";
if (elementValue == "" || elementValue == " " || elementValue== NULL){
email_err = "true";
}
var elementValue = document.getElementById("phone-for-registration").value;
if ((elementValue == "" || elementValue == " " || elementValue== NULL) && email_err == "true"){
if (errors == 0){
error = "Both email and contact cannot be left empty.";
}
else{
error += "<br>Both email and contact cannot be left empty.";
}
errors+=1;
}
var elementValue = document.getElementById("password-for-registration").value;
var elementName = document.getElementById("password-for-registration");
if (elementValue == "" || elementValue == " " || elementValue== NULL){
if (errors == 0){
error = "Password shouldn't be left empty.\nSelect a strong password atleast 6 characters long.";
}
else{
error += "<br>Password shouldn't be left empty.Select a strong password atleast 6 characters long.";
}
errors+=1;
}
else if (elementValue.length<6){
if (errors == 0){
error = "Password less than 6 characters aren't allowed for security reasons.";
}
else{
error += "<br>Password less than 6 characters aren't allowed for security reasons.";
}
errors+=1;
}
email_err = document.getElementById("confirm-password-for-registration").value;
var elementName = document.getElementById("confirm-password-for-registration");
if (elementValue != email_err){
if (errors == 0){
error = "The password to confirm doesn't match with your desired password.";
}
else{
error += "<br>The password to confirm doesn't match with your desired password.";
}
errors+=1;
}
var elementValue = document.getElementById("agreed-for-registration");
var elementName = document.getElementById("agreed-for-registration");
if (!elementValue.checked){
if (errors == 0){
error = "Please go through our <a href=''>Terms and Conditions</a>, and make sure you agree to continue.";
document.getElementById("agreed-for-registration").focus();
}
else{
error += "<br>Please go through our <a href=''>Terms and Conditions</a>, and make sure you agree to continue.";
}
errors+=1;
}
alert(errors);
if (errors > 1){
document.getElementById("form_errors").innerHTML = "<h4 style='color:red;'>Please remove the following errors from form to continue.</h4>";
document.getElementById("form_errors").innerHTML += "<h5>" + error + "</h5><br>";
return false;
} else if (errors == 1){
alert(error);
elementName.focus();
return false;
} else if (errors == 0){
return true;
}
return false;
}
Function called here.
<form name="registration" class="deco_blu_form" action="<?=$base_url;?>forms/confirm-registration/members.php" method="post" onsubmit="return formValidator();">
Please ask if any other information, code or explanation is required.
FIDDLE
You need to have elementValue === "NULL" or elementValue == null
I put console.log instead of alert and onblur trigger just for me to debug easier.
So the full code is:
function formValidator() {
var elementValue = document.getElementById("first-name").value;
var elementName = document.getElementById("first-name");
var errors = 0;
var error = " ";
if (elementValue == "" || elementValue == " " || elementValue === "NULL") {
error = "First Name shouldn't be left empty.";
errors = 1;
}
var elementValue = document.getElementById("last-name").value;
var elementName = document.getElementById("last-name");
if (elementValue == "" || elementValue == " " || elementValue === "NULL") {
if (errors == 0) {
error = "Last Name shouldn't be left empty.";
} else {
error += "<br>Last Name shouldn't be left empty.";
}
errors += 1;
}
var elementValue = document.getElementById("email-for-registration").value;
var elementName = document.getElementById("email-for-registration");
var email_err = "false";
if (elementValue == "" || elementValue == " " || elementValue === "NULL") {
email_err = "true";
}
var elementValue = document.getElementById("phone-for-registration").value;
if ((elementValue == "" || elementValue == " " || elementValue === "NULL") && email_err == "true") {
if (errors == 0) {
error = "Both email and contact cannot be left empty.";
} else {
error += "<br>Both email and contact cannot be left empty.";
}
errors += 1;
}
var elementValue = document.getElementById("password-for-registration").value;
var elementName = document.getElementById("password-for-registration");
if (elementValue == "" || elementValue == " " || elementValue === "NULL") {
if (errors == 0) {
error = "Password shouldn't be left empty.\nSelect a strong password atleast 6 characters long.";
} else {
error += "<br>Password shouldn't be left empty.Select a strong password atleast 6 characters long.";
}
errors += 1;
} else if (elementValue.length < 6) {
if (errors == 0) {
error = "Password less than 6 characters aren't allowed for security reasons.";
} else {
error += "<br>Password less than 6 characters aren't allowed for security reasons.";
}
errors += 1;
}
email_err = document.getElementById("confirm-password-for-registration").value;
var elementName = document.getElementById("confirm-password-for-registration");
if (elementValue != email_err) {
if (errors == 0) {
error = "The password to confirm doesn't match with your desired password.";
} else {
error += "<br>The password to confirm doesn't match with your desired password.";
}
errors += 1;
}
var elementValue = document.getElementById("agreed-for-registration");
var elementName = document.getElementById("agreed-for-registration");
if (!elementValue.checked) {
if (errors == 0) {
error = "Please go through our <a href=''>Terms and Conditions</a>, and make sure you agree to continue.";
document.getElementById("agreed-for-registration").focus();
} else {
error += "<br>Please go through our <a href=''>Terms and Conditions</a>, and make sure you agree to continue.";
}
errors += 1;
}
console.log(errors)
if (errors > 1) {
document.getElementById("form_errors").innerHTML = "<h4 style='color:red;'>Please remove the following errors from form to continue.</h4>";
document.getElementById("form_errors").innerHTML += "<h5>" + error + "</h5><br>";
return false;
} else if (errors == 1) {
alert(error);
elementName.focus();
return false;
} else if (errors == 0) {
return true;
}
return false;
}
At first, I count the following fields:
first-name
last-name
email-for-registration
phone-for-registration
password-for-registration
confirm-password-for-registration
agreed-for-registration
Just in case if you do something with the absolute value.
I have built a small prove-of-concept script and encountered that this script doesn't work, if you don't have an element with id #form_errors. Could this be your problem? This way the call for document.getElementById("form_errors") would result in undefined, and the function would not return false.
The same check for undefined elements holds of course for the other fields, too ;)

Categories

Resources