function validator()
{
var f = document.forms.suform.elements.fn.value;
if(f==null || f=="" || f==" ") //condition 1
{
alert("First name is required!");
return false;
}
else if(!(/^[a-zA-Z ]{2,30}$/,test(f))) // condition 2
{
alert('Invalid First Name');
return false;
}
//Some other conditions
}
I called it as
<form method="post" name="suform" onsubmit="return validator()" action="register.php">
<input placeholder="First Name" name="fn" type="text" id="fname" maxlength=20>
//other inputs
</form>
Now the problem is condition 2 is not working and as long as it is there the conditions below it also dont work,
the second i delete condition 2 everything starts running fine.
There is some error in regex checking.
(/^[a-zA-Z ]{2,30}$/.test(f))
Period will come before the test()
Related
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;
}
I am trying to test my form for validation. I don't have an .asp or .php file so I was informed I could use action="". My code doesn't seem to function right.On codepen it shows as values being posted. Jsfiddle gives me an error thats a paragraph long. In browser the page just seems to refresh. I have no alerts showing for anything....
what am I doing wrong here?
HTML:
<form name="name_form" action="" onsubmit="ValidateFormJS()" method="post">
First Name:
<input type="text" name="first_name">
<br> Last Name:
<input type="text" name="last_name">
<br>
<input type="submit" value="Submit">
</form>
Javascript:
function ValidateFormJS() {
var first = document.forms["name_form"]["first_name"].value;
var last = document.form["name_form"]["last_name"].value;
if (first == null || first == "") {
alert("First name must be filled out.");
return false;
} else if (last == null || last == "") {
alert("Last name must be filled out.");
return false;
} else {
alert("Form Submitted.");
return true;
}
}
The returned values from the function are never used.
You forgot return before the function call on onsubmit event.
onsubmit="return ValidateFormJS()"
Another problem is that you're using document.form to get the value of last name. It should be document.forms.
The last else can be removed.
Demo
var form = document.forms["name_form"];
function ValidateFormJS() {
var first = form["first_name"].value,
last = form["last_name"].value;
if (first == null || first == "") {
alert("First name must be filled out.");
return false;
} else if (last == null || last == "") {
alert("Last name must be filled out.");
return false;
}
}
<form name="name_form" action="" onsubmit="return ValidateFormJS()" method="post">
First Name:
<input type="text" name="first_name">
<br>Last Name:
<input type="text" name="last_name">
<br>
<input type="submit" value="Submit">
</form>
try this
in view
<form name="name_form" action="" onsubmit="return ValidateFormJS();" method="post">
in js code
function ValidateFormJS() {
var first = document.forms["name_form"]["first_name"].value;
var last = document.form["name_form"]["last_name"].value;
if (first == null || first == "") {
alert("First name must be filled out.");
return false;
} else if (last == null || last == "") {
alert("Last name must be filled out.");
return false;
}
alert("Form Submitted.");
return true;
}
Why are my conditional statements not working properly? I want to display bothe error messages at the same time.
function validate() {
if (firstName.value == "") {
document.getElementById('error').innerHTML = "*Field is empty";
return false;
} else if (lastName.value == "") {
document.getElementById('errorTwo').innerHTML = "*Field is empty";
return false;
} else {
return true;
}
}
<form name="form" action="action.php" method="post" onsubmit="return validate()">
<div class="wrapper">
<span>Name</span>
<br>
<input type="text" name="firstName" id="firstName" placeholder="First Name" onfocus="this.placeholder=''" onblur="this.placeholder='First Name'" />
<label id="error"></label>
<br>
<input type="text" name="middleName" id="middleName" placeholder="Middle Name (optional)" onfocus="this.placeholder=''" onblur="this.placeholder='Middle Name (optional)'" />
<input type="text" name="lastName" id="lastName" placeholder="Last Name" onfocus="this.placeholder=''" onblur="this.placeholder='Last Name'" />
<label id="errorTwo"></label>
<br>
<br>
</div>
Your conditional statements are working correctly, your understanding of them is a little off though.
An if / else if statement will stop running when a condition is matched, so if firstName.value is empty, then that if statement will be matched and the code will exit there and not evaluate the rest of the conditions.
You want to use independent conditional statements for each test, and instead of returning either true or false, set a variable to true or false and return that after the conditional checks.
So...
function validate()
{
var valid = true;
if(firstName.value=="")
{
document.getElementById('error').innerHTML="*Field is empty";
valid = false;
}
if(lastName.value=="")
{
document.getElementById('errorTwo').innerHTML="*Field is empty";
valid = false;
}
return valid;
}
Just a note on the code itself, the above comments are mainly correct, if you post your entire code, you'll probably get more helpful responses. Also, you can eliminate the =="" part of the checks and just test the value of the variable as an empty string evaluates to false.
Don't chain the validations together with if-else otherwise if the first name validation fails, then you will never check the last name validation.
Help yourself by quickly creating a JsFiddle :-)
Here it is:
http://jsfiddle.net/23tnpve4/1/
You will easily see some issues by trying:
As others mentioned, missing brackets etc
As others mentioned, if the first test fails the other fields are not checked so errors can by corrected only step by step.
There is no code that refreshes your error DIVs. In a new form check, the error fields have to be cleared first. Checking forms are cycles with several possible start statuses.
Try to collect the status of fields in an array and work them later, something like this:
window.validate = function()
{
var firstName = document.getElementById('firstName');
var lastName = document.getElementById('lastName');
// Clear
firstName.val('');
lastName.val('');
// Check
var errorNames = [];
if(firstName.value=="")
{
errorNames.push('firstName');
}
if(lastName.value=="")
{
errorNames.push('lastName');
}
// Inform
for (var i=0; i<errorNames.length; i++) {
document.getElementById(errorNames[i]).innerHTML="*Field is empty";
}
// Return value
return errorNames.length == 0;
}
The concept of this code will work more intuitively. I haven't checked it against typos, it is a draft, but I do hope it will help you.
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().
I have a very strange problem. Inside form I have hidden input with value -1 and input field for username.
<form action="" method="POST" name="login" onSubmit="return Validate()">
<input type="text" id="username"/>
<input type="hidden" id="available" value="-1"/>
< input type="submit" value="Send"/>
</form>
On submit function Validate() checks value of username input which mustn't be empty, and Validate() also checks value of available input which mustn't be valued -1.
function Validate(){
var a=document.getElementById("username").value;
var b=document.getElementById("available").value;
if(a=="" || a==null)
{
alert("Username cannot be empty");
return false;
}
else if(b<0)
{
alert("Form isn't finished");
return false;
}
else
{
return true;
}
}
Problem is that Validate() works only if one condition is evalueted. If function Validate() contains only 1 var(a or b) and 1 if order(without else if) it works correctly. But when I put it like this, when Validate uses a and b variables and if, else if conditional order it won't work. Really od.. Thanks in advance...
In this case it works:
function Validate(){
var a=document.getElementById("username").value;
if(a=="" || a==null)
{
alert("Username cannot be empty");
return false;
}
else
{
return true;
}
}
<input type="hidden" id="available" value="-1"/>
Here the value is of string dataType. Whereas
else if(b<0) //b is string dataType
Hence it failed. so change it as
var b= Number(document.getElementById("available").value);
Try like this
HTML:
<form action="" method="POST" name="login">
<input type="text" id="username" />
<input type="hidden" id="available" value="1" />
<input type="button" value="Send" onClick="return Validate()" />
</form>
JS:
function Validate() {
var a = document.getElementById("username").value;
var b = Number(document.getElementById("available").value);
if (a == "" || a == null) {
alert("Username cannot be empty");
return false;
} else if (b < 0) {
alert("Form isn't finished");
return false;
} else {
document.login.submit(); //dynamically submit the form
}
}
If you are wanting to get error notifications for each input don't use if/else here, use multiple if's and set your errors
function validate(){
var a=document.getElementById("username").value;
var b=document.getElementById("available").value;
var errors = [];
if(a=="" || a==null){
errors.push("Invalid username");
}
if(b<0 || isNaN(b)){
errors.push("Invalid available value");
}
if(errors.length>0) {
//do something with errors (like display them
return false;
}
}
Using the else if one of them evaluates to true it will skip the others. For instance if the first one is empty or null then it will do that block and skip the others.
I was testing your code for IE and Firefox and it work. Just add parseInt when you get the value of var b.
var b= parseInt(document.getElementById("available").value);