How to solve client side validation problem? - javascript

I am working on a project and need to do some client side validation.
I am doing all validations by calling the onsubmit() method.
The problem that I am facing is that the validation runs just fine when I put into comments a few other statements but not otherwise.
My code:
var speak1=document.forms["form"]["speak1"].value
b = checkSpeakLanguages(speak1);
if(b==false){
return false;
}
which calls checkSpeakLanguage works properly.
But the following code works only when the above is put in comments:
var m= document.forms["form"]["maritalStatus"].value
b = checkMaritalStatus(m);
if(b==false){
return false;
}
Please help me. Please tell me why both the second part does not work when the other is present.

If the first b returns false, you return before the second part can execute. Combine the functions for your submit handler to something like:
function checkSubmit(){
var cansubmit = true,
speak1 = document.forms["form"]["speak1"].value,
m = document.forms["form"]["maritalStatus"].value;
if(!checkSpeakLanguages(speak1) || !checkMaritalStatus(m)) {
cansubmit = false;
}
return cansubmit;
}

Related

Using Jquery DataTable when assigning to variable

I'm going through an issue with Jquery DataTables.
I have several DataTables, but I want to assign only one of them to another variable and use it.
Small code for exemple below:
var time = "morning";
var helloTable;
var goodMorningTable = $('#goodMorning').DataTable({
...
});
var goodAfternoonTable = $('#goodAfternoon').DataTable({
...
});
var goodEveningTable = $('#goodEvening').DataTable({
...
});
function sayHello(time) {
switch(time) {
case "morning":
helloTable = goodMorningTable;
break;
case "afternoon":
helloTable = goodAfternoonTable;
break;
case "evening":
helloTable = goodEveningTable;
break;
}
helloTable.draw(); // And do more things with it
}
$('#btnAfternoon').on('click', function () {
sayHello("afternoon");
});
My code is more complicated than that but follows more or less the same structure. My DataTables data come from the server (AJAX).
In debug mode I can see that the draw() instruction is executed but nothing happens. I see that nothing happens because there is no "loading" time.
Please tell me if it's not clear enough.
What can you suggest to make it work?
Thanks in advance.

Page reloads before reaching else statement in javascript

The problem in the code below resides in the if...else statement. If a user tries to create an account with a username or email already present in localStorage the program displays an error message. This works fine however if the if statement is false the page reloads before reaching the else statement. I have used console.log to check whether the else statement is run however as stated above the page reloads before ever reaching the else statement. I have also tried putting event.preventDefault in the if statement however that doesnt work either. Any help would be greatly appreciated. Thanks in advance.
Edit: the function is called using onclick in html when the button is pressed.
function storeRegistrationInfo(){
let person = {};
person.fullname = document.getElementById("regFullName").value;
person.username = document.getElementById("regUserName").value;
let username = document.getElementById("regUserName").value;
person.email = document.getElementById("regEmail").value;
person.password = document.getElementById("regPassword").value;
person.repeatedPassword = document.getElementById("repeatPassword").value;
let per = JSON.parse(localStorage.getItem(username));
if (person.username === per.username || person.email === per.email){
document.getElementById("signUpStatus").innerText = "Username or Email already taken!";
}else {
localStorage[person.username] = JSON.stringify(person);
}
event.preventDefault();
}
Andre, you are not receiving the event object.
Assume you are triggering this as part of onClick() ?
Try adding :
function storeRegistrationInfo(event)
Maybe need to add:
if( !(person === undefined) &&(person.username === per.username || person.email === per.email))

CRM: Javascript to Check Email Validation and Prevent Saving if not Valid

On CRM 2013 on-premise, I'm working to write a javascript that checks for email validation. The field can contain a list of email address, however if the email is not valid, it will not let the users save the form.
I got the splitting and validating to work fine now.
However I continue to have problems to prevent users from saving the form.
On the OnChange, I check the box on the "Pass execution context as first parameter"
I user the preventDefault() function as suggested by an MSDN article however I keep getting error message "Unable to get property 'preventDefault' of undefined or null reference".
Any idea is appreciated. Here's my code:
function EmailTest(EmailField)
{
var Email = /^([a-zA-Z0-9_.-])+#([a-zA-Z0-9_.-])+\.([a-zA-Z])+([a-zA-Z])+/;
if(Email.test(EmailField))
{
return true;
}
else
{
return false;
}
}
function CheckEmailString(context)
{
try
{
var EmailString = context.getEventSource().getValue();
if (EmailString != null)
{
var separator = [" ", ",", ";", "|"];
var EmailArray = EmailString.split(separator);
var Flag = true;
for(var i = 0;i < EmailArray.length;i++)
{
if(!EmailTest(EmailArray[i]))
{
Flag = false;
break;
}
}
if(Flag != true)
{
alert("The list of emails entered contain invalid email format. Please re-enter");
context.getEventArgs().preventDefault();
}
}
}
catch(err)
{
alert(err.message);
}
}
you get the error
Unable to get property 'preventDefault' of undefined or null reference
because the getEventArgs is available only when you are inside the save event, it's not available inside onchange event.
You should add the validation check also inside the save event if you want to stop the save.
Could I suggest you might try updating it to the full version of the method ie
Xrm.Page.context.getEventArgs.preventDefault().
I understand when working in CRM you have to reference use the full names in order for your function to see the prevent default method.
Hopefully that helps but if not good luck in seeking a solution

Jquery domain validation after adding http

I need to do a URL validation for a CS form. I already have a script there that that checks for http and adds it if not there. However, if I add another function to do just validation, no matter where I put it, it returns URL invalid.
This is what I am running
<script type="text/javascript">
$(function(){
$('.url').blur(function(e) {
if ($(this).val().match(/^http/) || $(this).val().match(/^https/)) /*define the http & https strings */ {
$.noop() /*if strings exist, do nothing */
}
else {
// get value from field
var cur_val = $(this).val();
// do with cur_val
$(this).val('http://' + cur_val);
}
});
});
</script>
This is the second function I used for validation:
<script type="text/javascript">
function validate() {
var url = document.getElementById("url").value;
var pattern = /(ftp|http|https):\/\/(\w+:{0,1}\w*#)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%#!\-\/]))?/;
if (pattern.test(url)) {
alert("Url is valid");
return true;
}
alert("Url is not valid!");
return false;
}
</script>
What am I doing wrong? I've tried to merge the 2 functions but my js skills choose that exact moment to fail.
Thank you!
I don't know, if this is what you are exactly looking for,
var pattern = /(ftp|http|https):\/\/(\w+:{0,1}\w*#)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%#!\-\/]))?/;
pattern.test("http://google.com"); // True
pattern.test("google.com"); // False
The if condition you are using is useless, since you return the result of the pattern match anyway.
So the updated Validate function should simply return the pattern results & should look like:
function validate() {
var url = document.getElementById("url").value;
var pattern = /(ftp|http|https):\/\/(\w+:{0,1}\w*#)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%#!\-\/]))?/;
return pattern.test(url);
}
Assuming that there is a DOM element with id url.
Just from an immediate look, it looks like your "add http" function is looking for tags with class="url", while the validate function is looking for tags with id="url". If you have nothing with that id, then I suppose it would always return invalid.

How to not submit a form if validation is false

How can I make sure the form won't submit if one of the validations is false?
$('#form').submit(function(){
validateForm1();
validateForm(document.forms['dpart2']);
validateForm(document.forms['dpart3']);
});
$('#form').submit(function(){
return (validateForm1() &&
validateForm(document.forms['dpart2']) &&
validateForm(document.forms['dpart3']))
});
Basically, you return false in the event handler function.
If the function returns false, form won't be submitted.
$('#form').submit(function(){
return validateForm1()
&& validateForm(document.forms['dpart2'])
&& validateForm(document.forms['dpart3']);
}
});
Okay, some of the other solutions will have a lazy fail... you probably want all your validation to run, so that all errors are displayed. The presumption is that your validation methods will return false if they fail.
$("#myform").submit(function() {
var ret = true;
ret = validateForm1() && ret;
ret = validateForm(document.forms['dpart2']) && ret
ret = validateForm(document.forms['dpart3'])) && ret
return ret;
});
This way all your validators will be called, but the Boolean value for any failure, will result in a fail.
If validateForm(...) and validateForm1() return a boolean (true means that no validation error occurred), then you try to do that :
$('#form').submit(function(){
if (!validateForm1() || !validateForm(document.forms['dpart2']) || !validateForm(document.forms['dpart3'])) {
return false;
}
});
A thought that comes up automatically: Even if you implemented thorough client side validation be prepared to receive any invalid request data on the server that you can possibly imagine.
Client-side validation never keeps you from server-side validation. It is just a bonus in usability.

Categories