Form input check Javascript - javascript

I have an html form and want to create a Javascript code that would check if the Tel. field include only numbers. It is an exercise so I don't want to use jQuery or any other library. I put together this:
HTML
<form action="" method="post" enctype="multipart/form-data" name="form1" id="form1" onsubmit="return numberedFieldsCheck()">
<table>
<tr>
<td>
<label for="tel">Telephone</label></td>
<td>
<input type="text" placeholder="00441293603275" name="tel" id="tel" />
<span id="telFieldIntCheck" style="display:none;color:red">You can only use numbers.</span>
</td>
<td>
<input type="submit" name="button" id="button" value="Submit" />
</td>
</tr>
</table></form>
JS
function numberedFieldsCheck(){
var x=document.getElementById('tel').value;// retrieving value from the form
console.log(x);
if(!integerCheck(x)){
alert('wrong format');
document.getElementById('telFieldIntCheck').style.display="inline";
return false;
}
}
function integerCheck(userInput) {
var userInputArr=userInput.split('');
for (i=0;i<userInputArr.length;i++){
if (typeof userInputArr[i]=="number")
{console.log('format ok')}
else {return false};
}
}
Can you help me with the code? It alerts wrong format regardless of what I put into the input field. Console logs appear for a millisecond and disappear straight away.

Since you only need to check if the field contains only numbers, this should work :
function numberedFieldsCheck(){
var x=document.getElementById('tel').value;
// Checks if the field is empty.
if(x.trim() == '') {
alert("Tel field can't be empty.");
return false;
}
if(!integerCheck(x)){
alert('Wrong format !');
document.getElementById('telFieldIntCheck').style.display="inline";
return false;
}
alert("Alright !");
// Note that this return true is important. You weren't
// returning anything even in the case where everything was fine.
// If you don't, it will return 'undefined' by default, which is
// casted to 'false' in checks. So that means the function returns
// false even if everything is alright.
return true;
}
function integerCheck(userInput) {
// Now, all the elements of usrInputArr will contain strings only.
// That means typeof <element> will always return "string".
var userInputArr=userInput.split('');
for (i=0;i<userInputArr.length;i++){
char = userInputArr[i];
// Comparing by ASCIIs should work just fine.
if (! (char >= '0' && char <= '9' || char == ' ') )
return false;
}
return true;
}
You should also do what #hindmost said in the comments of your question i.e. changing the forms onsubmit to return numberFieldCheck().

Related

How to perform string methods on function parameter in javascript

I am trying to write some javascript code to validate an HTML form and I am stuck. I am suspecting there are multiple issues (I am really new to JS) but the one I am stuck at is preventing me from further troubleshooting. Essentially, I need to have 2 functions, validatePassword and validateForm, one to validate the password and another to validate the rest of the input. The password needs to have an uppercase letter and be at least 8 characters long.
My main problem right now is that I do not know how to convert validatePassword's parameter to a string to check its length and whether it has an uppercase letter or not.
(Please let me know if you see any other problems with my code.)
Here it is:
// add validatePassword function here
function validatePassword(str) {
let value = String(str);
if (value.length < 8 && value !== value.toLowerCase()) {
return true;
}
return false;
}
const validateForm = (myForm) => {
// get text of fields
var firstname = myForm.firstname.value;
var lastname = myForm.lastname.value;
var password = myForm.password.value;
firstname != null
? true
: $("#message").html("Please enter a first name");
lastname != null
? true
: $("#message").html("Please enter a last name");
/* Form validation*/
validatePassword(password) == true
? true
: $("#message").html("Password incorrect");
return false; // prevent page reload
};
<head>
<script src="https://code.jquery.com/jquery-3.6.3.min.js"></script>
</head>
<body>
<form id="form1" action="#" onsubmit="return validateForm(this);">
first name: <input type="text" name="firstname" /><br />
last name: <input type="text" name="lastname" /><br />
password: <input type="text" name="password" /><br />
<button>Check</button>
</form>
<hr />
<div id="message"></div>
</body>
A few problems here:
There was a logic error in validatePassword (and some typos). You want the password to be invalid if the length is < 8 or the value is equal to its lowercase. Personally I would return true is the password was valid, but to each their own.
It is more conventional to use if statements instead of the ternary operator if you don't need its return value.
You need to reset the error message string if nothing is wrong in the form (this can be done before checking any of the fields).
// add validatePassword function here
function validatePassword(str) {
let value = String(str);
if (value.length < 8 || value === value.toLowerCase()) {
return true; // invalid password
}
return false; // valid password
}
const validateForm = (myForm) => {
// get text of fields
var firstname = myForm.firstname.value;
var lastname = myForm.lastname.value;
var password = myForm.password.value;
$("#message").html("");
if (!firstname) {
$("#message").html("Please enter a first name");
}
if (!lastname) {
$("#message").html("Please enter a last name");
}
/* Form validation*/
if (validatePassword(password) === true) {
$("#message").html("Password incorrect");
}
return false; // prevent page reload
};
<head>
<script src="https://code.jquery.com/jquery-3.6.3.min.js"></script>
</head>
<body>
<form id="form1" action="#" onsubmit="return validateForm(this);">
first name: <input type="text" name="firstname" /><br />
last name: <input type="text" name="lastname" /><br />
password: <input type="text" name="password" /><br />
<button>Check</button>
</form>
<hr />
<div id="message"></div>
</body>
Few observations/suggestions :
As password is always consider as a sensitive field, It should be a type of password instead of text. (No need to worry about the data type while getting it, You will get it as a string only)
As per the mentioned validation criteria for password The password needs to have an uppercase letter and be at least 8 characters long. Condition should be :
value.length <= 8 && value !== value.tolowerCase()
myForm.password.value will return a string only. Hence, No need to convert String into a String again.
Your final password validation function would be :
function validatePassword(value) {
return (value.length <= 8 && value !== value.tolowerCase()) ? true : false;
}

Insert missing letter javascript game

I'm making a language learning game with javascript. I want the user to be able to write the missing letter and the results to be validated through javascript if they are right or wrong.
<form>
De<input id="letterone" type="text" name="latter" pattern="[A-Za-z]{1}">
ign<input id="lettertwo" type="text" name="latter" pattern="[A-Za-z]{1}">r
<input type="submit">
</form>
My javascript code.
if ((getElementById('letterone')==='s') && (getElementById('lettertwo')==='e')) {
alert('Correct');
}else{
alert('Wrong');
}
There are number of errors on your code :
No 'document' before getElementById
No 'value' after the object
No click handler
Incorrect id while accessing the object
Using input type=submit causes an unwanted page refresh as Useless Code comments below.
document.getElementById('submit').addEventListener('click', function() {
if ((document.getElementById('latterone').value==='s') && (document.getElementById('lattertwo').value==='e')) {
alert('Correct');
}else{
alert('Wrong');
}
});
<form>
De<input type="text" id="latterone" pattern="[A-Za-z]{1}">
ign<input type="text" id="lattertwo" pattern="[A-Za-z]{1}">r
<input type="button" id="submit" value="Submit">
</form>
var lOne = document.getElementById('letterone').value; // get the value of the first input
var lTwo = document.getElementById('lettertwo').value; // get the value of the second
if (lOne === 's') && lTwo === 'e') {
alert('Correct');
}else{
alert('Wrong');
}

I have to press submit button twice in IE using jquery framework to submit form

I have a strange behaviour in IE browser.
I have simple form:
<form name="test" id="test" action="some_url_here" method="post">
<input type="text" name="url" id="url" class="required" />
<input type="text" name="page" id="page" class="required" />
...
<input type="submit" name="submit" value="Submit" />
</form>
and in JS:
var result = true;
$("#test").on("submit", function(){
$(".required").removeClass("error");
$.each($("input.required"), function(k, v) {
if($(this).val() === '') {
$(this).addClass("error");
result = false;
return false;
}
});
if(result) {
if(!IsValidUrl($("input[name='url']").val()){
$("input[name='url']").addClass("error");
return false;
}
} else {
return false;
}
});
Let's assume that I filled all fields correctly.
In Chrome & Firefox, when I press on submit button then works fine, just once time.
In IE (all versions) I have to press two times on the submit form to execute/sumbit the form.
Why ?
I tried also to put after IsValidUrl condition:
$(this).submit();
But no success.
You have two options here. On both you need to stop the submit event and validate the form.
One is to go through all the fields in the form, add the class error to the invalid ones (if there's any), set the variable result and return (or submit if everything is alright).
The other is to stop the test at the first invalid field found, not using the variable result, and return (or submit if everything is alright).
JS
$(function () {
$("#test").on("submit", function (e) {
// Stop the submit, because you need to validate the form before proceeding.
e.preventDefault();
// Check the comments below to decide for the use of the variable.
var result = true;
$(".required").removeClass("error");
$.each($("input.required"), function (k, v) {
// Test for empty fields or, if it's the URL, check whether is valid.
if ($(this).val() === "" || ($(this).attr("name") == "url" && !IsValidUrl($(this).val())) {
// Add class error to the invalid fields.
$(this).addClass("error");
// At this point, you could just return false stopping the loop,
// or keep going to make sure all the invalid fields will get the
// class error. In this case, you can still use the variable result.
result = false;
// Keep going, so, no return.
// return false;
}
});
// If you decided to carry on through all the fields, and don't return
// false at the first error, test for the result value.
// As this is the case...
if (!result) return false;
else $(this).submit();
// If you didn't return previously...
// $(this).submit();
});
});

JavaScript Form Validation Not Working onSubmit

I'm working through a section of a book on form validation with JavaScript. Unfortunately, the example in the book isn't working. I understand and follow the logic behind the validation (The general idea is that if any of the individual field validation functions return a value to the validate function then an alert will display and the form will not be submitted onSubmit) , but nothing is happening onSubmit. I have looked over the script and html a few times and can't find anything wrong (I even went to the book site and copied the code from there).
Here is the html form and the JavaScript validation:
<script>
function validate(form)
{
fail = validateForename(form.forename.value)
fail += validateSurname(form.surname.value)
fail += validateUsername(form.username.value)
fail += validatePassword(form.password.value)
fail += validateAge(form.age.value)
fail += validateEmail(form.email.value)
if (fail == "") return true
else {alert(fail); return false }
}
</script>
<script>
function validateForename(field) {
if (field == "") return "No Forename was entered.\n"
return ""
}
function validateSurname(field) {
if (field == "") return "No Surname was entered.\n"
return ""
}
function validateUsername(field) {
if (field == "") return "No Username was entered.\n"
else if (field.length < 5) return "Usernames must be at least 5 characters.\n"
else if (/[^a-zA-Z0-9_-]/.test(field)) return "Only a-z, A-Z, 0-9, - and _ allowed in Usernames.\n"
return ""
}
function validatePassword(field) {
if (field == "") return "No Password was entered.\n"
else if (field.length < 6) return "Passwords must be at least 6 characters.\n"
else if (! /[a-z]/.test(field) || ! /[A-Z]/.test(field) || ! /[0-9]/.test(field)) return "Passwords require one each of a-z, A-Z and 0-9.\n"
return ""
}
function validateAge(field) {
if (isNAN(field)) return "No Age was entered.\n"
else if (field < 18 || field > 110) return "Age must be between 18 and 110.\n"
return ""
}
function validateEmail(field) {
if (field == "") return "No Email was entered.\n"
else if (!((field.indexOf(".") > 0) && (field.indexOf("#") > 0)) || /[^a-zA-Z0-9.#_-]/.test(field)) return "The Email address is invalid.\n"
return ""
}
</script>
</head>
<body>
<table class="signup" border="0" cellpadding="2" cellspacing="5" bgcolor="#eeeeee">
<th colspan="2" align="center">Signup Form</th>
<form method="post" action="adduser.php" onSubmit="return validate(this)">
<tr><td>Forename</td><td><input type="text" maxlength="32" name="forename" /></td>
</tr><tr><td>Surname</td><td><input type="text" maxlength="32" name="surname" /></td>
</tr><tr><td>Username</td><td><input type="text" maxlength="16" name="username" /></td>
</tr><tr><td>Password</td><td><input type="text" maxlength="12" name="password" /></td>
</tr><tr><td>Age</td><td><input type="text" maxlength="3" name="age" /></td>
</tr><tr><td>Email</td><td><input type="text" maxlength="64" name="email" /></td>
</tr><tr><td colspan="2" align="center">
<input type="submit" value="Signup" /></td>
</tr></form></table>
</body>
</html>
nothing is happening onSubmit
Assuming that you really do mean that nothing is happening, and that that includes "the form being submitted" then the problem is one that could be resolved by making the HTML valid.
A form cannot be wrapped around table rows and be inside the table those rows belong to. Some browsers recover from this error my moving the form to after the table (but leaving the inputs inside the table). This means that the inputs are not inside the form and sit around doing nothing.
As a quick fix, move the form so it surrounds the table.
As a proper solution, stop using tables for layout. CSS is a good tool for form layout.
You should also take advantage of the label element, and not fill your JS with globals.
Here's a hint.. how do you spell "isNAN"?
This code is easily debugged by putting alert statements after each line of code. If you use simple debugging like this, you will find that you have some invalid syntax. I leave it to you to find the bug!
Replace isNAN with isNaN and it should work.

Check if multiple functions are true, then do something

I am stuck on what I thought was a simple PEBCAK error on my part. I am trying to verify all of my functions are true before I submit a form, but cannot figure for the life of me what is wrong. Below is my javascript code:
function checknewaccount(){
if(emailvalid()&& checkname() && passwordcheck())
{
return true;
}
else{
return false;
}
}
function emailvalid()
{
if(email condition)
{
return true;
}
else {
return false;
}
}
function checkname())
{
if(name condition)
{
return true;
}
else {
return false;
}
}
function passwordcheck(){
if(password condition)
{
return true;
}
else {
return false;
}
}
html below:
<form id="newaccount" name="newaccount" method="post" onSubmit="accountcode.php">
<input type="text" id="email" onBlur="emailvalid()"/>
<input type="text" id="username" onBlur="checkname()" />
<input type="password" id="password" onkeyup="passwordcheck()"/>
<input type="submit" value="New" onClick="return checknewaccount()"/>
</form>
When i click "New, nothing happens, and I know the accountcode.php is not running, because nothing happens on the database end and there are no errors reported.
To sum up, my question is how checknewaccount() does not work? Does it have something to do with how I am calling them?
I am new to javascript so if I am completely off on my implementation, I apologize. Thank you very much for the help!
you've got the form syntax wrong - onsubmit = the name of the js function to call, action = the url...
<form action="accountcode.php" id="newaccount" name="newaccount" method="post" onSubmit="return checknewaccount()">
<input type="text" id="email" onBlur="emailvalid()"/>
<input type="text" id="username" onBlur="checkname()" />
<input type="password" id="password" onkeyup="passwordcheck()"/>
<input type="submit" value="New"/>
</form>
Fully tested code:
<html>
<head>
<script type="text/javascript">
function checknewaccount() {
return emailvalid() && checkname() && passwordcheck();
}
function emailvalid() {
var emailAddress = document.getElementById('email').value;
return (emailAddress=='test');
}
function checkname() {
return true;
}
function passwordcheck() {
return true;
}
</script>
</head>
<body>
<form action="#" onsubmit="return checknewaccount();">
<input type="text" id="email" name="email"/>
<input type="submit"/>
</form>
</body>
</html>
The form in the above code will only submit if the textbox has a value of test
A slightly better implementation would be:
<html>
<head>
<script type="text/javascript">
function checknewaccount() {
if(emailvalid() && checkname() && passwordcheck()) {
return true;
} else {
document.getElementById('validation').innerHTML = 'Validation failed!';
return false;
}
}
function emailvalid() {
var emailAddress = document.getElementById('email').value;
return (emailAddress=='test');
}
function checkname() {
return true;
}
function passwordcheck() {
return true;
}
</script>
</head>
<body>
<div id="validation"></div>
<form action="#" onsubmit="return checknewaccount();">
<input type="text" id="email" name="email"/>
<input type="submit"/>
</form>
</body>
</html>
As this at least tells the user the form wasn't submitted. Even better would be to give the user a more detailed reason why but that's beyond the scope of this question...
This part's fine (I took the liberty of fixing the indentation):
function checknewaccount(){
if(emailvalid()&& checkname() && passwordcheck())
{
return true;
}
else{
return false;
}
}
Although you could improve it:
function checknewaccount(){
return emailvalid() && checkname() && passwordcheck();
}
This part is a syntax error (to put it mildly):
function emailvalid(), checkname(), passwordcheck(){
if(condition){
return true;}
else{return false;}
If that's not a real quote from your code, you'll have to update your question (though I may not be here by then to update this answer). Not much point in asking about code and then quoting pseudo-code in the question. (At the very least, the pseudo-code is missing the final }.)
The same sort of thing is true for your functions in the form:
function emailvalid()
{
if(email condition)
{
return true;
}
else {
return false;
}
}
That's fine (assuming that email condition is still psuedocode), but there's no need for the if:
function emailvalid()
{
return email condition;
}
In terms of "nothing happens," make sure you have debugging tools you can use. Chrome has Dev Tools built in, just press Ctrl+Shift+I. For Firefox, you can install the excellent Firebug. Recent versions of IE have dev tools built into them as well (for older versions you can download a free version of Visual Studio that can plug into the browser). Any of these will tell you about syntax and other errors, let you walk through your code statement-by-statement, etc., which is crucial to figuring out what's happening.
Here's a quickly dashed-off version of what I think you're trying to do. I wouldn't do it this way, but I've made the minimal changes to make it work:
HTML:
<form action="http://www.google.com/search"
method="GET" target="_blank"
onsubmit="return checknewaccount()">
<input type="text" id="email" name='q' onblur="emailvalid()">
<input type="text" id="username" onblur="checkname()" >
<input type="password" id="password" onkeyup="passwordcheck()">
<input type="submit" value="New">
</form>
Notes on that:
As Basiclife pointed out, your form code has issues. Those are fixed above.
Above I've used action="http://www.google.com/search" but of course for you it would be action="accountcode.php" (or at least, I think it would).
Use onsubmit for the form submission handler, not onclick on the submit button. You can't cancel a form submission reliably cross-brower via the submit button's onclick.
In onsubmit, make sure you use return — e.g., onsubmit="return checknewaccount()", not onsubmit="checknewaccount()" — because we want to make sure the event stuff sees the return value. We don't care if the event stuff doesn't see the return value of our other checks (onblur="emailvalid()"), but if we did, we'd need returns there as well.
Only one of the fields above has a name attribute; none of yours do. Only fields with name attributes get submitted with forms. I've only used one name for my example because I only want to submit one field to Google, but for your purposes, you're going to want name attributes on all three fields. This brief article has a discussion of id vs. name and what they're for. You sometimes want both.
I've put the attributes in all lower-case, which is best practice (and required if you want to use XHTML).
However, I've removed the / from the ends of the inputs. This is a bit off-topic, but at the apparent level you're working at, you don't want to try to use XHTML, use HTML. Using XHTML correctly is technically difficult, both in authoring and server configuration, and even then you have to serve it as tag soup to IE or it won't handle it properly. XHTML has its place, but in the vast majority of cases, there's no reason to use it.
With the above combined with the JavaScript below, there's no purpose whatsoever to the handlers on the individual fields. I've left them, though, because I assume you're doing more than just the checks below — there's an example further down showing those handlers doing something useful.
JavaScript:
function checknewaccount() {
return emailvalid() && checkname() && passwordcheck();
}
function emailvalid() {
var element;
// Get the email element
element = document.getElementById('email');
// Obviously not a real check, just do whatever your condition is
return element.value.indexOf('#') > 0;
}
function checkname() {
var element;
// Get the username element
element = document.getElementById('username');
// Obviously not a real check, just do whatever your condition is
return element.value.length > 0;
}
function passwordcheck() {
var element;
// Get the username element
element = document.getElementById('password');
// Obviously not a real check, just do whatever your condition is
return element.value.length > 0;
}
Live copy
Things change slightly if the emailvalid, et. al., functions are going to do something to let the user know the fields are invalid, such as highlighting their labels:
HTML:
<form action="http://www.google.com/search"
method="GET" target="_blank"
onsubmit="return checknewaccount()">
<label>Email:
<input type="text" id="email" name='q' onblur="emailvalid()"></label>
<br><label>Username:
<input type="text" id="username" onblur="checkname()" ></label>
<br><label>Password:
<input type="password" id="password" onkeyup="passwordcheck()"/></label>
<br><input type="submit" value="New">
</form>
JavaScript:
function checknewaccount() {
var result;
// Because we're actually doing something in each of the
// three functions below, on form validation we want to
// call *all* of them, even if the first one fails, so
// they each color their field accordingly. So instead
// of a one-liner with && as in the previous example,
// we ensure we do call each of them:
result = emailvalid();
result = checkname() && result;
result = passwordcheck() && result;
return result;
}
function emailvalid() {
var element, result;
// Get the email element
element = document.getElementById('email');
// Obviously not a real check, just do whatever your condition is
result = element.value.indexOf('#') > 0;
// Update our label and return the result
updateLabel(element, result);
return result;
}
function checkname() {
var element, result;
// Get the username element
element = document.getElementById('username');
// Obviously not a real check, just do whatever your condition is
result = element.value.length > 0;
// Update our label and return the result
updateLabel(element, result);
return result;
}
function passwordcheck() {
var element, result;
// Get the username element
element = document.getElementById('password');
// Obviously not a real check, just do whatever your condition is
result = element.value.length > 0;
// Update our label and return the result
updateLabel(element, result);
return result;
}
function updateLabel(node, valid) {
while (node && node.tagName !== "LABEL") {
node = node.parentNode;
}
if (node) {
node.style.color = valid ? "" : "red";
}
}
Live copy

Categories

Resources