Javascript form validation not working for 2 input fields - javascript

I am trying to validate my form using javascript. I want that if a user leaves an input field empty then he will see an alert and the form will not submit data to php file. Unfortunatlly, the code below is not working for me. javascript is not executing on form submit.
javascript
<script>
function MyForm() {
var x =document.forms["myForm"]["name"].value;
if (x == null || x == "") {alert("Name must be filled out");
return false;
}
{ var y=document.forms["myForm"]["age"].value;
if (y == null || y == "") {
alert("age must be filled out");
return false;
}
}
form
<form name="myForm"action="game.php"onsubmit="return myForm()"method="post">
Name: <input type="text" name="name">
Age: <input type="text" name="age">
<input type="submit" value="Submit">
</form>
Any help is greatly appriciated.

You've got a couple typos in your code. A good way to find them is to use the console in the developer tools of your browser (try pressing F12).
Change
{ var y=document.forms["myForm"]["age"].value;
to
var y=document.forms["myForm"]["age"].value; //removed the opening curly brace
and in your form change:
onsubmit="return myForm()"
to
onsubmit="return MyForm()"

you have to invoke myForm function first to make it work
function MyForm() {
var x =document.forms["myForm"]["name"].value;
if (x == null || x == "")
{alert("Name must be filled out");
return false;
}
var y=document.forms["myForm"]["age"].value;
if (y == null || y == "") {
alert("age must be filled out");
return false;
}
}
MyForm(); // invoke it here

There are 2 typo issue in your javascript method. Try below method
function MyForm() {
var x = document.forms["myForm"]["fname"].value;
if (x == null || x == "") {
alert("Name must be filled out");
return false;
}
var y=document.forms["myForm"]["age"].value;
if (y == null || y == "") {
alert("age must be filled out");
return false;
}
}

Related

How to prevent form from sending when there are alerts showing? JavaScript

I created a contactus form on my website, and I have few js functions that check if the values are valid or not. What currently happens is - the functions do work, they check what they are supposed to, and the alert shows as well - But after all the alerts showed, it still submits the form.
I tried to use the Prevent method, and the window.back.history but none worked...
How can I fix it?
JavaScript part:
<script>
function validateForm1() {
var firstname = document.forms["contactus"]["fname"].value;
if (firstname == "") {
alert("Please provide your first name");
return false;
e.preventDefault();
window.history.back();
}
}
document.getElementById("gender").addEventListener('click',checkradio);
function checkradio() {
if(document.getElementById("genderm").checked == false && document.getElementById("genderf").checked == false && document.getElementById("gendero").checked == false ){
alert("Please select your gender");
return false;
e.preventDefault();
window.history.back();}
}
function checkbox(){
if (document.querySelector('#cbr:checked') == null){
alert("Please choose a subject");
return false;
e.preventDefault();
window.history.back();
}
function agecheck(){
var x = document.forms["contactus"]["age"].value;
var y = 18;
if(x<y)
{
alert("Please submit the form only if you're 18 yo");
return false;
e.preventDefault();
window.history.back();
}
}
}
</script>
My HTML part uses the submit method and links to:
<form id="contactus" name="contactus" action="http://jkorpela.fi/cgi-bin/echo.cgi" onsubmit="validateForm1();checkbox();checkradio();agecheck()" style="float:right;text-align: right; direction: rtl;">
I think you can put 'return' in 'onsubmit'.
<script>
function validateForm1() {
var firstname = document.forms["contactus"]["fname"].value;
if (firstname == "") {
alert("Please provide your first name");
return false;
}
if (document.getElementById("genderm").checked == false && document.getElementById("genderf").checked == false && document.getElementById("gendero").checked == false) {
alert("Please select your gender");
return false;
}
if (document.querySelector('#cbr:checked') == null) {
alert("Please choose a subject");
return false;
}
var x = document.forms["contactus"]["age"].value;
var y = 18;
if (x < y) {
alert("Please submit the form only if you're 18 yo");
return false;
}
}
</script>
<form id="contactus" name="contactus" action="http://jkorpela.fi/cgi-bin/echo.cgi" onsubmit="return validateForm1();" style="float:right;text-align: right; direction: rtl;"></form>
In your form for each you can use the required tag so they always have to input something into the field.
For example
<input type="text" id="username" name="username" required>

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

How to make input required

What I want is that when both fields i.e. fname and lname are kept empty, the pop-up window should show both messages i.e. "First name must be filled out", "Last name must be filled out".
What modifications do I need to do?
<!DOCTYPE html>
<html>
<head>
<script>
function validateForm() {
var x = document.forms["myForm"]["fname"].value;
if (x == null || x == "") {
alert("First name must be filled out");
document.myForm.fname.focus();
return false;
}
var y = document.forms["myForm"]["lname"].value;
if (y == null || y == "") {
alert("Last name must be filled out");
document.myForm.lname.focus();
return false;
}
}
</script>
</head>
<body>
<form name="myForm" action="demo_form.asp" onsubmit="return validateForm()" method="post">First name:
<input type="text" name="fname">Last name:
<input type="text" name="lname">
<input type="submit" value="Submit">
</form>
</body>
Perhaps this will give you some ideas about how to proceed:
function validateForm() {
var errors = [],
fname = document.forms["myForm"]["fname"],
lname = document.forms["myForm"]["lname"];
if (lname.value == "") {
errors.unshift("Last name must be filled out");
lname.focus();
}
if (fname.value == "") {
errors.unshift("First name must be filled out");
fname.focus();
}
if (errors.length > 0) {
alert("Cannot submit\n" + errors.join("\n"));
return false;
}
}
Demo: http://jsfiddle.net/MKdg5/
The first thing you'll notice is that it is easier to read because blocks are indented. Also:
You currently use document.forms["myForm"]["fname"] and document.myForm.fname to access the same field. Pick one way and use it consistently, or
Create a variable that references the field, fname, and then use fname.value and fname.focus()
Don't bother testing for null because the .value property never will be.
Instead of immediately alerting an error and returning, add the error text to an array and then at the end test if the array is empty.
You can go with Hthml 5 required. It's so much simpler and neat.
<form>
First name: <input type="text" name="fname" required="required">
Last name: <input type="text" name="lname" required="required">
<input type="submit" value="Submit">
</form>
Demo
Note: The required attribute is supported in Internet Explorer 10, Firefox, Opera, and Chrome. But it is not supported in Internet Explorer 9 and earlier versions, or in Safari.
Try to validate your field as:
if (!x || x.length == 0)
BAsed on your validateForm function, your code would never check the second field. When using the return statement, the function will stop executing, and return the specified value.
A solution is use nested if statements and check both fields in one conditional block
if (x==null || x=="")
{
if (y==null || y=="")
{
//codes for both are not validated
}
else
{
//codes for just x is not validated
}
}
else
if (y==null || y=="")
{
//codes for y is not validated
}
else
{
//codes for all validated
}
This way use of return statement in each block won't break your function execution

Javascript alert on submit if text field is empty

So i want to alert the user if they submit the form with an empty text field
HTML:
<form id="orderform">
<input type="text" name="initials" id="initials" maxlength="3">
<p class="center">
<input type="image" src="#" id="submitbutton" name="submit" value="Place Order">
</p>
</form>
Javascript:
$('#orderform').submit(function() {
if($('#initials').length == 0){
alert('Please fill out your initials.');
}
});
Just make sure you return false in there somewhere-
$('#orderform').submit(function() {
if($('#initials').val() == ''){
alert('Please fill out your initials.');
return false;
}
});
$('#initials').length will check if the element exists. Try this:
$('#orderform').submit(function() {
if($('#initials').val().length == 0){
alert('Please fill out your initials.');
}
});
as lewsid pointed out, you should also return false if you want to cancel the submit
$('#orderform').submit(function(e) {
e.preventDefault();
if(!$.trim((this + ' input').val()).length){
alert('Please fill all the fields');
return false;
}
return true;
});
but is better if you do this with pure JS not jQuery
function funnjsTrim(input) {
return input
.replace(/^\s\s*/, '')
.replace(/\s\s*$/, '')
.replace(/([\s]+)/g, '-');
}
validate_form = function(form, mssg){
mssg = form_errors[mssg] || 'Error: empty field';
var form_to = form.name,
elems = document.forms[form_to].getElementsByTagName("input");
for(var i = 0; i < elems.length + 1; i++) {
if(elems[i].type != 'submit') {
var string = funnjsTrim(elems[i].value);
if(!string.length) {
alert(mssg);
error = 'error';
return false
}
}
}
if(typeof error == "undefined"){
alert('Valid');
return true;
}
}
so in your html
<form onsubmit="return validate_form(this)">
in this line: if(elems[i].type != 'submit') add || elems[i].class != 'your input class' to add exceptions
I'd use e.preventDefault() instead of return false. Return false also prevents events from bubbling and can have unintended consequences if you don't understand this. Also nest that preventDefault within your if, no reason to stop submission if things are good.
$('#orderform').submit(function(e) {
if(!$.trim($(this).find('input[type="text"]').val()).length){
e.preventDefault();
alert('Please fill all the fields');
}
});

javascript:very simple validation does not working

I can't figure out why this is not working as i did everything correct.
This is a simple create a account form. I put validation code for some of the field like name, email and password. There are many other fields. but first i m trying this.
The like is here:
jsfiddle
and the code of HTML:
First Name
<input type="text" name="fname" id="fname"/>
<input type="text" name="lname" id="lname />
<input type="text" name="remail" id="remail" />
New Pasword
<input type="password" name="rpass" id="rpass" />
<input name="regis" type="submit" class="color2" id="id" value="Submit" />
The javascript code here:
function validateRegis() {
//regex for fname and lname
var fname = $("#fname").val();
var lname = $("#lname").val();
var patt_n = /[a-z]{2,20}/i;
//checking fname and lname for regex matching
var ftest = patt_n.test(fname);
var ltest = patt_n.test(lname);
var remail = $("#remail").val();
var filter = /^[a-zA-Z0-9]+[a-zA-Z0-9\_\.\-]+[a-zA-Z0-9\_\-]+#[a-zA-Z0-9]+[a-zA-Z0-9\.\-]+[a-zA-Z0-9]+\.[a-z]{2,4}$/;
var test = filter.test(remail);
var rpass = $("#rpass").val();
var patt = /[a-z0-9~!##$%^&*()_\ ]/i;
var test2 = patt.test(rpass);
if (fname === "" || ftest === false) {
alert("Please provide first name!");
$("#fname").focus();
return false;
} else if (lname === "" || ltest === false) {
alert("Please provide Last name!");
$("#lname").focus();
return false;
} else if (remail === "" || test === false) {
//
alert("Please provide email in correct format!");
$("#remail").focus();
return false;
} else if (rpass === "" || rpass.length < 8 || test2 === false) {
alert("Please provide password!");
$("#rpass").focus();
return false;
} else if ((fname !== "") & (lname !== "") & (remail !== "") & (test === true) & (rpass >= 8) & test2 === true) {
return true;
}
}
It needs jquery to run the code.
The problem is the validateRegis function is not available in the global scope.
In the fiddle UI left side panel, 2nd select box select No Wrap in body, it works fine.
Demo: Fiddle
When you select onLoad there, all the scripts under the script frame is wrapped under a anonymous function, so your validateRegis method becomes a local member of that anonymous function. Thus that function will not be available when the function submit is called causing an Uncaught ReferenceError: validateRegis is not defined error being thrown.

Categories

Resources