How to handle alphanumeric and null in JavaScript? - javascript

We are facing an issue on handling null, because if the value is null, it is not reaching the server. Below is the code snippet:
<input ... onchange="return checkEmpty(this);" />
And the JavaScript:
function checkEmpty(value) {
alert("Empty Check() "+value);
if (myTrim(value.length == 0)) {
alert("please Enter Value!"+ value +" value");
return false;
}
return true;
}
We are trying to display one popup for null value and the request should go to the server, but some exception is occurring we are unable to identify it and the request is not coming to server.

You can do this:
if (variable == null) {
// do something
}
--which is 100% equivalent to the more explicit but less concise:
if (variable === undefined || variable === null) {
// do something
}

While there are ways to solve this specific problem (and the other answer(s) manage to answer that), I'll try to address a more general one.
What you essentially want is the form control to not be empty. Well, you don't need JavaScript for that at all
<input ..... required>
That will prevent the form from submitting unless the required field was filled.
<form>
Try to submit me empty! <input required>
<button>I dare you!</button>
</form>

Related

Field validation for not null or empty is not triggering

I'm trying to send messaging to the user that a field is required if they fail to input a value. I want the error to be displayed on the field itself, rather than a global error message at the top of the page.
If I do not enter any data into the form, it still allows submission. However, if I do not enter a username but I do enter mismatched passwords, the username field receives the validation message "Passwords do not match".
So, it appears to me, that for some reason my code to check if the input is null is not passing as True and so the function continues to my next condition.
Why isn't this function catching nulls?
<form action="/register" method="post">
<div class="form-group">
<input autocomplete="off" autofocus class="form-control" name="username" placeholder="Username" type="text"
oninput="checkNull(this)" id="username">
</div>
<div class="form-group">
<input class="form-control" name="password" placeholder="Password" type="password" oninput="checkNull(this)"
id="password">
</div>
<div class="form-group">
<input class="form-control" name="confirmPassword" placeholder="Confirm Password" type="password"
oninput="check(this)" id="confirmPassword">
</div>
<script language='javascript' type='text/javascript'>
function check(input) {
if (input.value != document.getElementById('password').value) {
input.setCustomValidity('Passwords do not match');
} else {
input.setCustomValidity('');
}
}
if (input.value == "" || input.value == null) {
input.setCustomValidity('This field is required');
}
else {
input.setCustomValidity('');
}
</script>
<button class="btn btn-primary" type="submit">Register</button>
</form>
I've tried some additional troubleshooting. I split my functions out, one to check for matching passwords, one to check for no input. I realized that by calling them in the same function I was comparing each to the password which is a problem.
As a sanity check, I then set to check for a specific string "foo". When passing in "foo", the error displays as expected, so I know at least the function is getting called.
I then tried to use "===" to compare the value rather than "==", but that didn't work either.
Code updated to reflect most recent changes.
When submit your form, it is not calling check() function. So, if you not touch any input, they will not be validated.
You can solve this by adding onsubmit="return validate()" to <form /> tag:
<form action="/register" method="post" onsubmit="return validate()">
Your validation function could be simple as:
var isValid = true;
function validate() {
isValid = true;
document.querySelectorAll('.form-control').forEach(check);
return isValid;
}
Notice the return keyword. When return value is false the submitting action will be cancelled. check() function should also mutate isValid variable:
function check(input) {
if (input.value == "" || input.value == null) {
input.setCustomValidity('This field is required');
isValid = false;
}
else if (input.type == 'password' && input.value != document.getElementById('password').value) {
input.setCustomValidity('Passwords do not match');
isValid = false;
}
else {
input.setCustomValidity('');
}
}
Also, you should only check if passwords are the same if you are validating a password input.
You can accomplish this by adding the extra condition to password validation: input.type == 'password'
You are calling your check method onchange, if you do not enter any text in the username field, your check method will not be called. So, the simple way to do this is to add required attribute on all your fields.
If you want to do it using JS, look at onsubmit method that gets triggered when the form's submit button is clicked.
Also, you should have three different methods for validating each of your fields. It will be hard to maintain and you will be cramping up one method with various checks.
You are using deprecated techniques here.. You should never attach a function to a form element in-line (within the html tag).
When it comes to checking password on keyup, you could use something like this with jquery:
var pwInputs = $(this).find('input[type=password]');
$('input[type=password]').keyup(() => {
pwarr = new Array();
pwInputs.each(function() {
pwarr.push($(this));
});
if (pwarr[0].val() != pwarr[1].val()) {
// Do work
}
if (pwarr[0].val() == null || pwarr[0].val() == "" & pwarr[1].val() == null || pwarr[1].val() == "") {
// Do Work
}
});
You could use jquery in a similar fashion to check values on submit.
$('#formid').on('submit', function() { // Do work })

ASP.NET UserControl javascript is not loading HTML to its variable

I have created UserControl that I wish to use on multiple pages. This control contains classic javascript but for some reason it will not load element to a variable. Client IDs look ok.
This is button that activates javascript:
<input type="submit" name="ctl00$ContentPlaceHolder1$ContactList$btn_NewContact" value="Potvrdit" onclick="javascript:return CheckContactName();" id="ContentPlaceHolder1_ContactList_btn_NewContact" class="MyButton" style="color:white;" />
This is the textbox:
<input name="ctl00$ContentPlaceHolder1$ContactList$con_fullname" type="text" id="ContentPlaceHolder1_ContactList_con_fullname" class="MyTextBox" />
This is Javascript function:
function CheckContactName() {
name = document.getElementById("ContentPlaceHolder1_ContactList_con_fullname");
if (name.value == '' | name.value == null) {
return false;
}
UploadContact();
return true;
}
Now, when I debug this in a console the name.value is undefined. The name variable itself is just "[object HTMLInputElement]".
So no matter what is in that textbox, this function is always false. I also checked all IDs inside final client page and there are no duplicates. Can you tell why this is? Thanks.
I supose you set the input's value in code behind right?
Anyways, you might try using document.querySelector, and it seems that your logical operator is wrong, you are using | instead of ||.
function CheckContactName() {
let name = document.querySelector(
'#ContentPlaceHolder1_ContactList_con_fullname'
);
if ((name.value == '') || (name.value == null) || (name == undefined)) {
return false;
}
UploadContact();
return true;
}
Changed name to cname.
It seems that when you use control on a page that already contains some JavaScript function and that function declares variable with the same name as the one in usercontrol - this happends.

Form validation for textfield not working?

In javascript, I´m supposed to create a function that checks if a textfield within a form is empty. If it is and the user clicks submit, the user will not be allowed to proceed. I found what I considered a suitable solution to this on w3schools (http://www.w3schools.com/js/js_validation.asp). I´ve checked more times than I can remember and everything seems to be in order, but it´s not working!! Instead, when the submit button is clicked, the website calls a different function I have in javascript which it is not supposed to do...
HTML code
Other code
<p>
<form method="post" name="form" action="" onsubmit="return validateName()">
<label for="fullName">Namn: </label><input id="fullName" class="text" name="namn" type="text"> </input>
</p>
<p>
<label for="epost">Epost: </label><input id="epost" class="text" name="epost" type="email"> </input>
</p>
<p>
<input id="submit" type="submit" value="Skicka"> </input>
</p>
</form>
Other code
Javascript code
function validateName() {
var a = document.forms["form"]["namn"].value;
if (a == null || a == "") {
alert("Name required");
return false;
} else {
return true;
}
}
Clicking the submit button should call this function above (validateName), but instead it calls this function:
function alert() {
return confirm("Do you really wish to leave this website?");
}
I´ve looked through my code multiple times and can´t find anything that seems to be out of place. Can any of you find anything wrong? And maybe suggest a solution that solves my problem so my function will work properly?
I would be very grateful if someone could help me resolve this matter!
alert is a predefined function that you are using correctly once and incorrectly the second time. Simply change the name of YOUR alert function to something else, or just use confirm as it was intended and leave out the function alert part
Correct:
alert("Name required");
Incorrect:
function alert() {
return confirm("Do you really wish to leave this website?");
}
one solution is to do this:
function confirm_leaving(){
return confirm("Do you really wish to leave this website?");
}
That's because you are calling the alert function within your validateName function.
function validateName() {
var a = document.forms["form"]["namn"].value;
if (a == null || a == "") {
alert("Name required"); //<- remove this
return false;
} else {
return true;
}
}
Well i think you may put this code instead of this : function validateName() {
To correct this just put a this command :
function validateName(this) {

Javascript can't locate HTML form ID

I'm creating a basic HTML form, and a Javascript form validator that looks for any input value in the "first name" field. The problem I'm having is that nothing seems to be working to return the first name form value to check it in JS.
Relevant HTML:
<form id="form1" name="formName">
First name:<br>
<input type="text" id="fn" >
<br>
Last name:<br>
<input type="text" name="ln" >
<br>
Email address: <span style="color:red">(required)</span><br>
<input type="text" name="email" >
<br><br>
<button onclick="validate()">Submit</button>
</form>
My JS:
var validate = function (){
var x = document.getElementById("fn").value;
if (x == null || "" || "undefined"){
alert("Please fill out your first name");
return false;
}
kickoff();
}
var kickoff = function () {
var visitor = document.forms["form1"].fn.value;
alert("Thanks for filling out, " + visitor +"\n");
return visitor;
};
Here's a JSFiddle.
My X variable is never reached, it seems, and keeps returning "undefined" when I submit the page. I've been fiddling with it for quite a while and can't seem to figure out what I'm doing wrong. Any help?
This doesn't mean what you think:
if (x == null || "" || "undefined") {
Can also be written as:
if ((x == null) || // might be false
"" || // will be false
"undefined" // will be true
) {
so the if will always be true.
You really just need:
if (! x) {
Besides the syntax issues, that method is also out-of-scope. You're not even going to be able to debug the issue with your conditional until you fix that.
You can either in-line the script higher up in the DOM or define validate directly on the window object:
window.validate = function () {
http://jsfiddle.net/frg37t3u/5/
Neither case is ideal, you should know. Globals are bad, but that's another discussion.

how to compare 2 form inputs live

I'm trying to compare two form inputs "password" and re-enter-password" to make sure there the same. I validate the password by sending it to a separate PHP that echoes back the results(which works fine)
<script type="text/javascript">
$(document).ready(function() {
$('#password_feedback').load('password-check.php').show();
$('#password_input').keyup(function() {
$.post('password-check.php', {
password: form.password.value
},
function(result) {
$('#password_feedback').html(result).show();
});
});
});
</script>
I tried sending password and re-enter=password to a PHP to compare with no luck. Can I compare the two with every keyup.
What are you checking for in your PHP script? Anything in particular that justifies the use of PHP?
You could do that only with JS, you don't need the AJAX part.
HTML :
<input type="password" id="password">
<input type="password" id="password_cf">
<div class="result"></div>
JS (jQuery) :
$('#password_cf').on('keyup', function(){
if($('#password_cf').val()== $('#password').val())
$('.result').html('They match');
else
$('.result').html('They do not match');
});
Fiddle : http://jsfiddle.net/2sapjxnu/
You can use the blur event if you want to only check once the focus is lost on that field. It's a bit less "responsive" than verifying on every key, but more performant I guess.
Not necessary jQuery, add the function:
function checkPass(input) {
if (input.value != document.getElementById('re-enter-password').value) {
input.setCustomValidity('Passwords should match.');
} else {
input.setCustomValidity('');
}
}
Add this to your re-enter-password: oninput="checkPass(this)"
OR
just call this function in the part where you want to make the comparison:
function checkPass() {
var input = document.getElementById('password');
if (input.value != document.getElementById('re-enter-password').value) {
input.setCustomValidity('Passwords should match.');
} else {
input.setCustomValidity('');
}
}
How about adding a class to each input and then:
if($(".password").val() == $(".re-enter-password").val()){
alert("it matches")
} else {
alert("no match yet");
}
Quick and dirty -
Given this markup -
<input type="password" name="pw1" />
<input type="password" name="pw2" />
You could check it client side without muliple round trips to the server using code like this -
$('[name="pw2"]').blur(function() {
var pw1 = $('[name="pw1"]').val();
var pw2 = $('[name="pw2"]').val();
if(pw2 != pw1) {
alert('passwords do not match');
}
});
Matching 2 form input fields with JavaScript by sending it off to the server to get an assertion response could render a bad user experience, because if you're doing this on each keyPress, then it generates unnecessary internet traffic - while the user is waiting.
So, instead, why not match these 2 fields directly with JavaScript?
If you are using a specific regular expression on the server for validation check as well, you can have the server put that regex "pattern" in the HTML fields - (no JavaScrpt needed for that). Then, onkeyup event you can simply do something like:
form.field2.onkeyup = function()
{
if (form.field1.value !== form.field2.value)
{
/* some code to highlight the 2 fields,
or show some message, or speech bubble */
return;
}
}
form.field1.onkeyup = form.field2.onkeyup;

Categories