Form is submitting even after failing Javascript validation? - javascript

I have a form called here:
<span class="aligncenter button">Submit</span>
And I have a JavaScript function here:
if (myForm == 'newIncident')
{
var vDemAge = document.forms['newIncident']['demAge'].value;
var vBibNumber = document.forms['newIncident']['bibNumber'].value;
// Run through validations before submitting form
validateTime();
validateDate();
validateAge();
validateGender();
validateLocation();
validateType();
validateDisposition();
if (vDemAge == 'Age' || vDemAge == '') // If Age is not entered, set the value to be blank
{
document.forms['newIncident']['demAge'].value = '';
}
if (vBibNumber == 'Bib #' || vBibNumber == '') // If Bib # is not entered, set the value to blank
{
document.forms['newIncident']['bibNumber'].value = '';
}
document.getElementById(myForm).submit();
}
else
{
document.getElementById(myForm).submit();
}
So I have each of the validations as a separate function that I am calling in sequence when submitting the form. If I comment out the "document.getElementById(myForm).submit();", the validations run as expected. However, if I leave it uncommented, it submits every time even if the validations fail. How can I stop this from happening?
Thanks!
EDIT:
So this is one of the validations I'm running. They're all structured the same way. Somewhere I should be returning a boolean true/false? How exactly would I insert that in this one below?
function validateDisposition()
{
var vIncidentDisposition = document.forms['newIncident']['incidentDisposition'].value;
if (vIncidentDisposition == '')
{
document.forms['newIncident']['incidentDisposition'].className = 'required';
}
else
{
document.forms['newIncident']['incidentDisposition'].className = 'formborder';
}
}

assuming your validation functions return a bool, you should have something like
if( validateTime() && validateDate() && validateAge()... etc ) {
if (vDemAge == 'Age' || vDemAge == '') // If Age is not entered, set the value to be blank
{
document.forms['newIncident']['demAge'].value = '';
}
if (vBibNumber == 'Bib #' || vBibNumber == '') // If Bib # is not entered, set the value to blank
{
document.forms['newIncident']['bibNumber'].value = '';
}
document.getElementById(myForm).submit();
}

I got it working! The boolean idea put me on the right path. Thanks!
I just added a "return true" and "return false" to each of the validations, then used the answer above with the "&&" if to build the logic into the myform "if". If it doesn't pass all of them the else does a "return false". Works like a charm!

Related

How can I use conditional logic with JavaScript form validation?

I have the following JavaScript function which is triggered by an onclickevent and is working fine.
<script>
function validateForm() {
let xgame_name = document.forms['myForm']['game_name'].value;
if (xgame_name == '') {
alert('Game Name must be filled out');
return false;
}
let xdev_name = document.forms['myForm']['developer_name'].value;
if (xdev_name == '') {
alert('Developer Name must be filled out');
return false;
}
let xdev_email = document.forms['myForm']['email'].value;
if (xdev_email == '') {
alert('Developer Email must be filled out');
return false;
}
let xdemo_rom = document.forms['myForm']['demo_rom'].value;
if (xdemo_rom == '') {
alert('Demo Rom must be uploaded');
return false;
}
let xpromo_image = document.forms['myForm']['promo_image'].value;
if (xpromo_image == '') {
alert('Promo must be uploaded');
return false;
}
}
</script>
I am trying to add this so if one of the radio buttons with a value of 1 is selected on the form it will check an additional field to see if there is a value and show an alert.
let xcartridge = document.forms['myForm']['cartridge'].value;
if (xcartridge == '1') {
let xcover_art = document.forms['myForm']['cover_art'].value;
if (xcover_art == '') {
alert('If Cartridge is selected you must proved Cover Art');
return false;
}
}
This follows the same syntax of the above code example that is working but this does not send an alert but rather the form validation does not work at all. How can I get the alert to show when one fields condition is met, where it is 1 and that prompts an alert on an additional field?

Sending message from plugin to form not working for empty values

I'm sending a custom message from a plugin (that does some validation) back to the CRM form.
Here's my plugin code that executes on pre-Update and post-Create:
//GetAccounts is a simple method to return accounts based in specified crtitias.
//In Update event, it will add an extra filter to exclude the current account...
const string DupeFieldName = "new_approval_status";
if (xrmObjects.PluginContext.PrimaryEntityName == Xrm.Account.EntityLogicalName && xrmObjects.PluginContext.Depth == 1 && (xrmObjects.PluginContext.MessageName == "Update" || xrmObjects.PluginContext.MessageName == "Create"))
{
Entity account;
account = (Entity)xrmObjects.PluginContext.InputParameters["Target"];
if (account.Attributes.Contains("name"))
{
if (GetAccounts(account, xrmObjects.PluginContext.MessageName, "name", account["name"], xrmObjects.Service).Entities.Count > 0)
{
SetDupeMessage(account, Name);
return;
}
}
if (account.Attributes.Contains("websiteurl"))
{
if (GetAccounts(account, xrmObjects.PluginContext.MessageName, "websiteurl", account["websiteurl"], xrmObjects.Service).Entities.Count > 0)
{
SetDupeMessage(account, WebSiteExist);
return;
}
}
if (account.Attributes.Contains("new_linkedin"))
{
if (GetAccounts(account, xrmObjects.PluginContext.MessageName, "new_linkedin", account["new_linkedin"], xrmObjects.Service).Entities.Count > 0)
{
SetDupeMessage(account, LinkedIn);
return;
}
}
account[DupeFieldName] = string.Empty;
}
The simple method that sets the attributes' value...
private void SetDupeMessage(Entity account, string message)
{
account[DupeFieldName] = message;
account["new_approved"] = false;
}
And in my form, I have put this event handler on the onChange event of the new_approval_status:
function dupeDetected(context) {
var dupeStatus = Xrm.Page.getAttribute('new_approval_status').getValue();
if (!dupeStatus || dupeStatus == '') {
Notify.remove('duplicateWarning'); //Notify is a library that adds notification at form level...
return;
}
var messageParts = dupeStatus.split('|');
var message = messageParts[1];
var fieldName = messageParts[0];
Notify.add(message, 'ERROR', 'duplicateWarning', null);
};
This triggers fine when new_approval_status goes from null, empty to something. But it doesn't trigger on the other way around, a string to an empty string or null.
In my plugin, I've tried setting new_approval_status to string.Empty or null but the event doesn't trigger that way around.
Any ideas ?
You could set your field to something like OK instead.
This also allows to guarantee your code works ("is the field empty because it's supposed to be, or something is missing and it isn't being filled ?")

Stop form whitespace when user pressing submit

Okay, so I have a form. Applied a function to it.
All I want to do is when the form is submitted it launches the function, it checks to see if there is white space and throws out a message. I have the following:
function empty() {
var x;
x = document.getElementById("Username").value;
if (x == "") {
alert("Please ensure you fill in the form correctly.");
};
}
<input type='submit' value='Register' onClick='return empty()' />
<input type='text' id="Username" />
This is fine for if someone pressed the space-bar once and enters one line of whitespace, but how do I edit the function so that no matter how many spaces of whitespace are entered with the space-bar it will always throw back the alert.
Thanks in advance. I am very new to JavaScript. So please be gentle.
Trim the string before testing it.
x = document.getElementById("Username").value.trim();
This will remove any whitespace at the beginning and end of the value.
I have made a function for the same, i added another checks (including a regular expresion to detect multiples empty spaces). So here is the code:
function checkEmpty(field){
if (field == "" ||
field == null ||
field == "undefinied"){
return false;
}
else if(/^\s*$/.test(field)){
return false;
}
else{
return true;
}
}
Here is an example working with jquery: https://jsfiddle.net/p87qeL7f/
Here is the example in pure javascript: https://jsfiddle.net/g7oxmhon/
Note: the function checkEmpty still be the same for both
this work for me
$(document).ready(function() {
$('#Description').bind('input', function() {
var c = this.selectionStart,
r = /[^a-z0-9 .]/gi,
v = $(this).val();
if (r.test(v)) {
$(this).val(v.replace(r, ''));
c--;
}
this.setSelectionRange(c, c);
});
});
function checkEmpty(field) { //1Apr2022 new code
if (field == "" ||
field == null ||
field == "undefinied") {
return false;
} else if (/^\s*$/.test(field)) {
return false;
} else {
return true;
}
}

javascript validation works for one value only

I am trying to validate two input fields in my form using javascript. But my functions checks only one value for null or empty string. It submits the form if the other value is empty. Why?
function checkFieldEmpty()
{
var a=document.forms["verifyURN"]["urnNumber"].value;
var b=document.forms["verifyURN"]["urnDate"].value;
if (a==null || a=="", b==null || b=="") //b field validates here, not a..?
{
return false;
}
return true; //function returns true even if a is empty..?
}
//Below function is called when submit button pressed in my form
function verifyURN()
{
if(checkFieldEmpty())
{
document.verifyURN.rDoAction.value = "<%=Constant.myPage%>";
document.verifyURN.submit();
}
else{
alert("Mandatory fields empty");
return false;
}
}
...
<form name="verifyURN"...
try add
alert(a.length);
alert(b.length);
before your
if (a==null || a=="", b==null || b=="") //b field validates here, not a..?
{
and you will have a better picture of what criteria to check.

How to change textContent via javascript?

I have a registration form page, and there is empty div i want to use to display errors. To check forms before triggering php script i use javascript:
function errorHandler(){
var loginIn;
var passIn;
loginIn = document.forms["regForm"]["login"].value;
passIn = document.forms["regForm"]["password"].value;
if (loginIn == "" || loginIn == null) {
alert("LOGIN CANNOT BE EMPTY");
return false;
}
}
It works fine, and alert message do appear when i call them like this:
<form name="regForm" action= "save_user.php" onsubmit="return errorHandler()" method="post">.
But there is as i mentioned before a div inside of the form: div id ="errorArea"></div> and when i try to put a text inside of this div like this:
function errorHandler(){
var loginIn;
var passIn;
var erorAreaMessage;
loginIn = document.forms["regForm"]["login"].value;
passIn = document.forms["regForm"]["password"].value;
erorAreaMessage = document.getElementById('errorArea').textContent;
if (loginIn == "" || loginIn == null) {
erorAreaMessage = "LOGIN CANNOT BE EMPTY";
return false;
}
}
Nothing happens, can someone explain me why?
You need to put the value inside the <div>. That can done by setting the innerHTML or textContent property to your error-message.
Try this -
...
if (loginIn == "" || loginIn == null) {
document.getElementById('errorArea').textContent = "LOGIN CANNOT BE EMPTY";
return false;
}}

Categories

Resources