Specifying validation for specific form in some page - javascript

I have a javascript function that validate a popup form before submit it. Unfortunately it's created to handle one popup form per page only.
In my case, i have two different popup forms, so i want to specify what to do and also for which one.
$.fn.goValidate = function() {
var $form = this,
$inputs = $form.find('input:text');
var validators = {
email: {
regex: /^[\w\-\.\+]+\#[a-zA-Z0-9\.\-]+\.[a-zA-z0-9]{2,4}$/
}
};
var validate = function(klass, value) {
var isValid = true,
error = '';
if (!value && /required/.test(klass)) {
error = 'This field is required';
isValid = false;
} else {
klass = klass.split(/\s/);
$.each(klass, function(i, k){
if (validators[k]) {
if (value && !validators[k].regex.test(value)) {
isValid = false;
error = validators[k].error;
}
}
});
}
return {
isValid: isValid,
error: error
}
};
var showError = function($input) {
var klass = $input.attr('class'),
value = $input.val(),
test = validate(klass, value);
$input.removeClass('invalid');
$('#form-error').addClass('hide');
if (!test.isValid) {
$input.addClass('invalid');
if(typeof $input.data("shown") == "undefined" || $input.data("shown") == false){
$input.popover('show');
}
}
else {
$input.popover('hide');
}
};
$inputs.keyup(function() {
showError($(this));
});
$inputs.on('shown.bs.popover', function () {
$(this).data("shown",true);
});
$inputs.on('hidden.bs.popover', function () {
$(this).data("shown",false);
});
$form.submit(function(e) {
$inputs.each(function() {
if ($(this).is('.required') || $(this).hasClass('invalid')) {
showError($(this));
}
});
if ($form.find('input.invalid').length) {
e.preventDefault();
$('#form-error').toggleClass('hide');
}
});
return this;
};
$('form').goValidate();
I'm pretty sure that it's all about this line:
$('form').goValidate();
Let's say that the first form id is form_1 and the second form_2.
What should i put in this line?
Something like this i guess:
$('form['form_1]').goValidate();
Hope it was clear, thanks !

You can use form id to target your form.
ex. if your first form has id form1 then you can write.
$('#form1').goValidate();
and same as second one.

Related

How can i change the Display type of a sublist field in a beforeLoad function?

Im trying to set the display type of a sublist field when the user is creating/viewing/editing an record.
This is for an Netsuite customization.
define(['N/ui/serverWidget'], function (serverWidget) {
function beforeLoad(serverWidget) {
if (scriptContext.type == scriptContext.UserEventType.VIEW ||
scriptContext.type == scriptContext.UserEventType.EDIT ||
scriptContext.type == scriptContext.UserEventType.CREATE) {
var form = serverWidget.createForm({
title: 'Movile - Requisition Costs Analyst'
});
var nomeFornecedor = form.getSublist({ id: 'item' }).getField({
id: 'vendorname'
});
nomeFornecedor.isDisabled = false;
}
}
return { beforeLoad: beforeLoad }
})
I expect to learn how to do that type of sublist editing.
Any help are apreciated!
define(['N/ui/serverWidget'], function (serverWidget) {
function beforeLoad(context) {
if (context.type == scriptContext.UserEventType.VIEW || context.type == scriptContext.UserEventType.EDIT || context.type == scriptContext.UserEventType.CREATE) {
var form = context.form;
form.title = 'Movile - Requisition Costs Analyst';
var nomeFornecedor = form.getSublist({ id: 'item' }).getField({
id: 'vendorname'
});
nomeFornecedor.updateDisplayType({displayType: serverWidget.FieldDisplayType.DISABLED});
}
}
return { beforeLoad: beforeLoad }
})

How to successfully call the submit when all validations are true

I have created a validation in javascript which detect if there's an empty field and if there's none then it will now insert into database which I use a PHP code.
But it does nothing I'm having trouble inserting into database, I think because I put e.preventDefault(), I put the e.preventDefault() so it will not reload and show the validation messages that I created.
(function() {
document.querySelector('#addForm').onsubmit = function (e) {
e.preventDefault();
const name = document.querySelector('#name');
const age = document.querySelector('#age');
const email = document.querySelector('#email');
//Check empty input fields
if(!document.querySelector('#name').value){
name.classList.add('is-invalid');
}else{
name.classList.remove('is-invalid');
}
if(!document.querySelector('#age').value)
{
age.classList.add('is-invalid');
}else{
age.classList.remove('is-invalid');
}
if(!document.querySelector('#email').value){
email.classList.add('is-invalid');
}else{
email.classList.remove('is-invalid');
}
}
})();
You should only e.preventDefault() if any of the inputs are empty then, example updated:
document.querySelector('#addForm').onsubmit = function(e) {
const name = document.querySelector('#name');
const age = document.querySelector('#age');
const email = document.querySelector('#email');
let formIsInvalid = false;
//Check empty input fields
if (!name.value) {
name.classList.add('is-invalid');
formIsInvalid = true;
} else {
name.classList.remove('is-invalid');
}
if (!age.value) {
age.classList.add('is-invalid');
formIsInvalid = true;
} else {
age.classList.remove('is-invalid');
}
if (!email.value) {
email.classList.add('is-invalid');
formIsInvalid = true;
} else {
email.classList.remove('is-invalid');
}
if (formIsInvalid) {
e.preventDefault();
}
}
You should append AJAX request to send values to the server
var th = $(this);
$.ajax({
type: "POST",
url: "handler.php", //Change
data: th.serialize()
}).done(function() {
alert("Thank you!");
setTimeout(function() {
// Done Functions
th.trigger("reset");
}, 1000);
});

Return false is not prevent calling form submitting in javascript

On a form submit I am calling following function.
function confirmSubmit() {
var checkedAtLeastOne = false;
var checkboxs = document.getElementsByName("reportColumns");
var reportId = $('#reportId').val();
console.log(checkboxs.length);
for(var i = 0, l = checkboxs.length; i < l; i++) {
if(checkboxs[i].checked) {
checkedAtLeastOne = true;
break;
}
}
if(checkedAtLeastOne) {
if(!reportId) {
alert('Report ID cannot be empty');
return false;
} else {
var xhttp = new XMLHttpRequest();
xhttp.open("GET", "checkreportid.action?reportId=" + reportId, true);
xhttp.send();
xhttp.onreadystatechange = function (e) {
if(xhttp.readyState == 4 && xhttp.status == 200) {
document.getElementById("checkreportid").innerHTML = xhttp.responseText;
var reportid = $('#reportid').val();
console.log("reportId->" + reportId);
console.log("reportid->" + $('#reportid').val());
if(reportid == reportId) {
alert("Duplicate Report ID!");
return false;
} else {
return true;
}
}
}
}
} else {
alert("You must select atleast one column");
//e.preventDefault();
return false;
}
}
Here if the reportid equals to reportId it gives the alert (Duplicate Report ID) but it calls the action. return false is not prevent calling the action.
I am calling the function as below.
<s:form action="savereport" namespace="/" validate="true"
onsubmit="return confirmSubmit()">
EDITED
Now I am trying following. If the report ID is empty it gives relevant alert message (Report ID cannot be empty). It it is not empty it calls the checkreportid action but it doesn't give duplicate error message even if there are duplicate report ids. It calls the form submitting action.
function confirmSubmit() {
var checkedAtLeastOne = false;
var checkboxs = document.getElementsByName("reportColumns");
var reportId = $('#reportId').val();
console.log(checkboxs.length);
for (var i = 0, l = checkboxs.length; i < l; i++) {
if (checkboxs[i].checked) {
checkedAtLeastOne = true;
break;
}
}
if (!reportId) {
alert('Report ID cannot be empty');
return false;
} else {
////////
$.ajax({
url: "<s:url action='checkreportid'/>",
type: "GET",
data: {reportId: reportId},
dataType: "text/javascript",
traditional: true,
statusCode: {
200: function (data) {
console.log(data.responseText);
document.getElementById("checkreportid").innerHTML = data.responseText;
var reportid = $('#reportid').val();
console.log("reportId->"+reportId);
console.log("reportid->"+reportid);
if (reportid==reportId) {
alert("Duplicate Report ID!");
return false;
} else {
if (!checkedAtLeastOne) {
return true;
} else {
alert("You must select atleast one column");
return false;
}
}
}
}
});
}
}
What am I missing with my code ?
This is due to the asyncronous nature of a XMLHttpRequest. You are returning false in a callback function, not in the onsubmit handler.
You should look into doing what you want without an XMLHttpRequest or use a syncronous request (this is not reccomended and disabled in some browsers).
The reccomended option is to stop the form submitting all the time with
e.preventDefault();
return false;
And to manually submit the form with a XMLHttpRequest in the original callback if you want to.
The reason is that XMLHttpRequest is aysnchronous.
Your call to
xhttp.send();
returns immediately and therefore that if-else branch doesn't have a return false.
The return statements in your code boil down to:
if(checkedAtLeastOne) {
if(!reportId) {
return false;
} else {
}
} else {
return false;
}
You should add preventDefault method to the form element like below.
<form onsubmit='event.preventDefault(); return confirmSubmit();'>
<input type='submit' />
</form>
Use return in onsubmit event to trigger return false action,
<form onsubmit = "return confirmSubmit()">
</form>

How to validate dropdown list using validator in js

I am trying to validate drop down in js. Here is my script code
$.validator.addMethod(
'drop_down_validation',
function (value, element) {
alert ("my_fun")
var val = $('#creative_offer_type').val();
alert (val);
if (value.length==0 && val=="") {
return false;
}
else return true;
},
$.format("must select atleast one value")
);
var form_rules = {
'creative[offer_type]' : {
required: true,
drop_down_validation: true
},
};
var form_messages = {
'creative_offer_type' : { required: 'You must specify Offer Type'},
};
Is is correct? I tried out like this, but doesn't show any response in UI.
For your reference
function JSFunctionValidate()
{
if(document.getElementById('<%=ddlView.ClientID%>').selectedIndex == 0)
{
alert("Please select ddl");
return false;
}
return true;
}
Just call this method in your dropdown..

Why does my form still submit when my javascript function returns false?

Here is my Javascript formvalidator function:
function companyName() {
var companyName = document.forms["SRinfo"]["companyName"].value;
if (companyName == ""){
return false;
} else {
return true;
}
}
function companyAdd() {
var companyAdd1 = document.forms["SRinfo"]["companyAdd1"].value;
if (companyAdd1 == ""){
return false;
} else {
return true;
}
}
function companyCity() {
var companyCity = document.forms["SRinfo"]["companyCity"].value;
if (companyCity == ""){
return false;
} else {
return true;
}
}
function companyZip() {
var companyZip = document.forms["SRinfo"]["companyZip"].value;
if (companyZip == ""){
return false;
} else {
return true;
}
}
function enteredByName() {
var enteredByName = document.forms["SRinfo"]["enteredByName"].value;
if (enteredByName == ""){
return false;
} else {
return true;
}
}
function dayPhArea() {
var dayPhArea = document.forms["SRinfo"]["dayPhArea"].value;
if (dayPhArea == ""){
return false;
}
}
function dayPhPre() {
var dayPhPre = document.forms["SRinfo"]["dayPhPre"].value;
if (dayPhPre == ""){
return false;
} else {
return true;
}
}
function dayPhSub() {
var dayPhSub = document.forms["SRinfo"]["dayPhSub"].value;
if (companyAdd1 == ""){
return false;
} else {
return true;
}
}
function validateForm() {
if (companyName() && companyAdd() && companyCity() && companyZip() && enteredByName() && dayPhArea() && dayPhPre() && dayPhSub()) {
return true;
} else {
window.alert("Please make sure that all required fields are completed.");
document.getElementByID("companyName").className = "reqInvalid";
companyName.focus();
return false;
}
}
Here are all of my includes, just in case one conflicts with another (I am using jquery for their toggle()):
<script type="text/javascript" src="formvalidator.js"></script>
<script type="text/javascript" src="autoTab.js"></script>
<?php
require_once('mobile_device_detect.php');
include_once('../db/serviceDBconnector.php');
$mobile = mobile_device_detect();
if ($mobile) {
header("Location: ../mobile/service/index.php");
if ($_GET['promo']) {
header("Location: ../mobile/service/index.php?promo=".$_GET['promo']);
}
}
?>
<script src="http://code.jquery.com/jquery-1.7.1.js"></script>
Here is my form tag with the function returned onSubmit:
<form method="POST" action="index.php" name="SRinfo" onsubmit="return validateForm();">
The validation works perfectly, I tested all fields and I keep getting the appropriate alert, however after the alert the form is submitted into mysql and sent as an email. Here is the code where I submit my POST data.
if($_SERVER['REQUEST_METHOD']=='POST') {
// Here I submit to Mysql database and email form submission using php mail()
It would seem to me that this line is likely blowing up:
companyName.focus();
The only definition I see for companyName is the function. You can't call focus on a function.
This blows up so the return false is never reached.
I would comment out all the code in the validation section and simply return false. If this stops the form from posting then there is an error in the actual code performing the validation. Add each part one at a time until the error is found.
My guess is the same as James suggests that you are calling focus on the function 'companyName'. The line above this seems to be trying to get the element from the document with the same name but you are not assigning this to a variable so that you can call focus on it.

Categories

Resources