Regex form checking with Javascript - javascript

I'm having some real difficulty with javascript.
What I'm trying to do is validate user input from an HTML form.
I have two events for html:
<form action="attendproc.asp" method="post" onSubmit="return validateForm(this)">
<input type="submit" id="submit" value="Submit" class="button" onClick="return submitForm()">
Here is my javascript:
//Confirm form submission
function submitForm() {
if (confirm("Are you sure you want to submit this form?") == false) {return false}
else {return true}
}
//Validate form input
function validateForm(form) {
fail = validDate(form.date.value)
fail += validNum(form.jsia.value)
fail += validNum(form.jsga.value)
fail += validNum(form.yvcia.value)
fail += validNum(form.yvcga.value)
if (fail == "") {return true}
else {alert(fail) return false}
}
function validDate(field) {
if (/^\d{2}\/\d{2}\/\d{4}$/.test(field) == false) {return "Invalid date format. Please enter a valid date.\n"}
else {return ""}
}
function validNum(field) {
if (isNaN(field)) {return "Invalid input. Please enter a valid integer.\n"}
else {return ""}
}
Notice that I'm using RegEx to validate my desired date format. I know for certain the submitForm() function works. My pain is from the other three functions. Please help!

Shaun
I finally fixed it.
//Confirm form submission
function submitForm() {
if (confirm("Are you sure you want to submit this form?") == false) {return false;}
else {return true;}
}
//Validate attendance form input
function validateAttendForm(form) {
fail = validDate(form.date.value);
fail += validNum(form.jsia.value);
fail += validNum(form.jsga.value);
fail += validNum(form.yvcia.value);
fail += validNum(form.yvcga.value);
if (fail == "") {return true;}
else {alert(fail); return false;}
}
function validDate(field) {
re = /^\d{1,2}\/\d{1,2}\/\d{4}$/;
if (re.test(field) == false) {return "Invalid date format. Please enter a valid date.\n";}
else {return "";}
}
function validNum(field) {
if (isNaN(field) || field != parseInt(field)) {return "Invalid input. Please enter a valid interger.\n";}
else {return "";}
}
It was an issue with the syntax I used for my validDate() function. It was pretty much a plug and play fix.

Apart from shady formating, there's definately one thing that will cause problems.
isNaN(field)
should be: isNaN(parseInt(field))
IsNaN evaluates to true only with NaN, and string is not a NaN. ParseInt attempts to parse an int from a string, and returns either a number, or a NaN.

Related

I want to add an alert in the if else statement. How do I do that?

I want to add an alert inside the if and else if. If the user does not enter anything in the prompt box the alert triggers. Also if the user enters a number the prompt it will say that the user entered a number. How do do that?
let myForm2 = document.querySelector('.form2');
let pDisplay1 = document.querySelector('.display4');
myForm2.addEventListener('submit', function(e) {
e.preventDefault();
let uname = document.querySelector('.inputName2').value;
if (uname == null) {
} else if (isNaN(uname) == false) {
} else {
pDisplay1.innerHTML = `Welcome to the program ${uname}`;
}
})
<p> Activity 6</p>
<form class="form2" method="get">
<label>Full Name: <input type="text" class="inputName2"></label>
<input type="submit">
</form>
<p class="display4"></p>
document.querySelector('.className').value will return a string.
string.trim() removes the whitespaces and if the length === 0 it means that the input is empty or has only whitespaces which you generally want to treat as empty. If you consider space is a valid input you don't have to use trim().
The + sign will convert a string into a number otherwise you could use parseInt(variable).
Number.isInteger(variable) will return true if the variable is an integer.
You could also write !isNaN(+uname) or +uname !== Number.NaN
myForm2.addEventListener('submit', function (e) {
e.preventDefault();
let uname = document.querySelector('.inputName2').value;
if (uname.trim().length === 0) {
alert('You should write something');
} else if (Number.isInteger(+uname)) {
alert('You wrote a number');
} else {
pDisplay1.innerHTML = `Welcome to the program ${uname}`;
}
});
Empty string is not equal to null, replace uname==null with uname=='', after the replacement, you can identify the situation that the user did not input, if it is more strict, you can also use trim to remove whitespace and then do condition review

Password validation is not working in the login form

Password validation is not working in the login form. Here is my code:
function verifyPassword() {
var str = document.getElementById("t1").value;
if (str.match(/[a-z]/g) &&
str.match(/[A-Z]/g) &&
str.match(/[0-9]/g) &&
str.match(/[^a-zA-Z\d]/g) &&
str.length >= 8)
return true;
else
return false;
}
You should call the function in the password field's change event and/or the form's submit event, not the form's click event. And you need to test the return value and do something.
document.getElementById('t1').addEventListener('change', function() {
if (!verifyPassword()) {
alert("Invalid password");
}
}
document.getElementByTagName('form')[0].addEventListener('change', function(event) {
if (!verifyPassword()) {
event.preventDefault();
alert("Invalid password");
}
}
Below you have a cleaner code and is checking your password, you must have: lowercase, uppercase character, and a number. The ^ symbol means that the password must be in this order: lowercase, uppercase, number and must be more than 8 characters.
The syntax ?=.*[x] means that you must have the condition x in your string.
Your old code was only checking if your string has any of these (lowercase, uppercase characters, numbers) but didn't put the condition that you must have all of these and for your password system this was useless.
function verifyPassword() {
var str = document.getElementById("t1").value;
var regEx = new RegExp("^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.{8,})");
if (regEx.test(str) &&
str.length >= 8)
console.log("good")
else
console.log("bad")
}
<div class="txt_field">
<input type="password" id="t1" value="" required>
<label>Password</label>
<button onclick="verifyPassword()">Verify</button>
</div>

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;
}
}

simple Form validation with javascript

I'm trying to create a simple HTML form & i want to use javascript to validate the values.
Here's the form tage:
<form action="" onSubmit="return formValidation();" method="Post" name="form">
Here's a part of the HTML form:
<label for="text">my text:</label>
<input type="text" name="text">
<div id="error"></div>
<input type="submit" value="submit">
& here's the formValidation() function:
function formValidation() {
var mytext=document.form.text;
if (textValidation(mytext, 3, 20)) {
}
return false;
}
& here's the textValidation() code:
function textValidation(txt, mn, mx) {
var txtlen = txt.value.length;
if (textlen == 0 || txtlen <=mn || txtlen > mx ) {
document.getElementById('error').innerHTML = '<h6 style="color: red;">text is invalid</h6>';
return false;
}
return true;
}
The problem is when i enter an invalid text, it shows the error but hitting the submit button again has no effect, even if i change the text.
i've used alert() & it worked fine.
what am i doing wrong?
You're setting the error text but you don't clear it so it just sticks around. Also, you have to return true in the if statement on your formValidation function otherwise it will always return false.
You can clear the message like this:
function textValidation(txt, mn, mx) {
var txtlen = txt.value.length;
if (textlen == 0 || txtlen <=mn || txtlen > mx ) {
document.getElementById('error').innerHTML = '<h6 style="color: red;">text is invalid</h6>';
return false;
}
document.getElementById('error').innerHTML = "";
return true;
}
Since formValidation always returns false, it will never allow the form to submit. That's fine for testing your JS, but later you'll want to use something like this:
function formValidation() {
var mytext=document.form.text;
if (textValidation(mytext, 3, 20)) {
return true;
}
return false;
}
You can write the form validate function like this
function formValidation() {
var mytext=document.form.text;
//if the variable boolval is initialized inside double quotes it is string now it is bool variable
var boolval=false;
if (textValidation(mytext, 3, 20)) {
boolval=true;
}
return boolval;
}
if textvalidation is true then it will initialize true to boolval or this function will return boolval false as we initialized before[which is default]
Your function formValidation() is always going to return false, regardless of the result of your conditional statement.
Consider your code, corrected in some ways:
function formValidation() {
var mytext=document.form.text;
if (textValidation(mytext, 3, 20)) {
}
return false;
}
If the function textValidation(mytext, 3, 20) is false, formValidation() returns false. If textValidation(mytext, 3, 20) is true, well... the body of the if statement executes, which is empty, and then formValidation returns false.
Additionally, there are also a number of mismatched parentheses and other syntax related issues in your code. Since Javascript is inherently flexible, you might miss these things in practice. I suggest using JSHint to validate and improve the general quality and design of your Javascript code.

JavaScript code returns false, but still the form is submittted

I have a form with JavaScript validation. Upon there being an error, the submit button should 'grey-out' and the form should not be submitted. However, the last couple of functions seem to submit the form even though they pop the alert box. Why?
Button code:
<input type="submit" name="button" id="button"
onclick='return formvalidation();' value="Next" />
Non-working function example:
function BlankSite() {
var SiteNum= document.getElementsByName("sitesinput")[0].value;
if ((SiteNum == "") || (SiteNum == 0))
{
alert("You have not selected an amount of sites.")
document.forms[0].button.disabled = true;
return false;
}
}
Function initiator:
function formvalidation()
{
ZeroPhones();
BlankPC();
BlankSite();
BlankSeats();
phone_change();
} // End of formvalidation
This is very strange and I have tried various workarounds all to no avail!
You need to have return false; in the function called by the onclick, in this case formvalidation.
Having some function called by the "root" function return false has no effect whatsoever. The return value is lost.
They are returning false (and breaking, which is actually unreachable code) but the results are never returned to parent validation function. Your validator, assuming it's bound to the form action, should look like:
function formvalidation(){
{
if (!ZeroPhones())
return false;
if (!BlankPC())
return false;
//
// keep checking for false and return false.
//
// default to return true
return true;
}
So when the functions do in-fact return false, the false return is carried back up through to the bound function.
BlankPC() is called by formvalidation so false is returned into the method formvalidation().
Your formvalidation() is always falling off the end which is the same as returning true.
If you want it to return false when one of your validations fails, it should be:
function formvalidation()
{
retval = true;
retval &= ZeroPhones();
retval &= BlankPC();
retval &= BlankSite();
retval &= BlankSeats();
retval &= phone_change();
return retval;
} // End
This can be optimized a bunch, but you can get the gist of it.
Call the JavaScript function onSubmit of the form instead of calling at button onClick.
JavaScript code
function validate()
{
alert('test');
return false;
}
<form action="test" method="post" onsubmit="return validate();">
This is working fine for me.
formvalidation() isn't returning false.
Maybe you want something like:
function formvalidation()
{
if(!ZeroPhones() ||
!BlankPC() ||
!BlankSite() ||
!BlankSeats() ||
!phone_change())
return false;
}
My solution to this problem was to disable the submit button until the validation was successful. Something along these lines:
function checkPassword() {
// This is my submit button
document.getElementById('nextBtn').setAttribute('disabled', 'disabled');
password1 = document.getElementsByName("pwd1")[0].value;
password2 = document.getElementsByName("pwd2")[0].value;
if (password1 == '') {
// If password not entered
alert ("Please enter Password");
return false;
} else if (password2 == ''){
// If confirmation password not entered
alert ("Please enter confirm password");
return false;
} else if (password1 != password2) {
// If NOT the same, return false.
alert ("\nPassword did not match: Please try again...");
return false;
} else {
document.getElementById('nextBtn').removeAttribute('disabled');
return true;
}
}

Categories

Resources