JS form validation function is not called inside onsubmit - javascript

I am trying to run a form validation on an HTML form with pureJS.
Here is my code:
<form name="myForm" action="" onsubmit="alert('hello world');return validateForm(myForm);">
<label>
<input name="username" placeholder="Name" type="text" required>
</label>
<label>
<input name="email" placeholder="Email" type="email" required>
</label>
<input type="submit" value="Submit 1">
<button type="submit">Submit 2</button>
<button>Submit 3</button>
function validateForm(formName) {
const form = document.forms[formName];
for(let i = 0; i < form.elements.length; i++){
const element = form.elements[i];
// validation fails if element is required and blank
if(element.attributes["required"] && !element.value.length){
element.focus();
return false;
}
// validation fails if email is not valid
if(element.getAttribute('type') === "email" && !validateEmail(element.value)) {
element.focus();
return false;
}
};
return true;
}
function validateEmail(str) {
var regexp = /[a-z0-9!#$%&'*+/=?^_`{|}~.-]+#[a-z0-9-]+(\.[a-z0-9-]+)*/;
return regexp.test(str);
}
new link without typo: http://jsfiddle.net/mech8bon/
http://jsfiddle.net/4bjmh9as/
Expected: to call the alert then the function.
Result: nothing called at all.

Open the developer tools in your browser. Look at the console. Read the error message.
Uncaught TypeError: Cannot read property 'elements' of undefined
You are passing the variable myForm:
validateForm(myForm);
But then you are treating it as a string containing a property name:
const form = document.forms[formName];
String literals need quotes around them:
validateForm('myForm');

The solution thanks to Ric and Quentin in this fiddle:
http://jsfiddle.net/eg89b02j/2/
<form name="myForm" action="" onsubmit="return validateForm(this);" novalidate>
The first fix was adding novalidate attribute to the form tag.
The second fix was making the form more generic by sending the form itself instead of name.

Related

Form before submit when using onsubmit function

I have this form
<form id="form" method="POST" onsubmit="return validate()">
<input type="text" id="name" name="name">
<input type="submit" value="next">
</form>
and this validation
if ($("#name").val() == "") {
return false;
}
return true;
what I am trying to do, is to disable the submit button, I tried to use submit function for the form but its not triggered, the problem is I don't have access to html or js files, only one custom.js file I can add or override other functions.
anyone can help me ?
Thanks
so if you have $("#name") probably you have the jquery library.
in this case you can try remove onsubmit html property directly and use this event from jquery. $("#form").submit(...) and there you can use your validation function with return boolean value
You can override the validate function (but it is a bit dirty):
function validate() {
console.log('default validator');
return false;
}
var defaultValidator = validate;
window.validate = function () {
defaultValidator();
console.log('custom validator');
return false;
};
<form id="form" method="POST" onsubmit="return validate()">
<input type="text" id="name" name="name">
<input type="submit" value="next">
</form>
Try this in your validate function.
$('#form>submit').prop('disabled', true);

Multiple form validation with same function

I am using form twice on same page.
HTML Code
<form action="post.php" method="POST" onsubmit="return checkwebform();">
<input id="codetext" maxlength="5" name="codetext" type="text" value="" placeholder="Enter here" />
<input class="button" type="submit" value="SUMBIT" />
</form>
It's working fine with one form but when i add same form again then it stop working. The second form start showing error popup alert but even i enter text in form field.
JS Code
function checkwebform()
{
var codecheck = jQuery('#codetext').val();
if(codecheck.length != 5)
{
alert('Invalid Entry');
} else {
showhidediv('div-info');
}
return false;
}
How can i make it to validate other forms on page using same function?
As I commented, you can't have more than one element with the same id. It's against HTML specification and jQuery id selector only returns the first one (even if you have multiple).
As if you're using jQuery, I might suggest another approach to accomplish your goal.
First of all, get rid of the codetext id. Then, instead of using inline events (they are considered bad practice, as pointed in the MDN documentation), like you did, you can specify an event handler with jQuery using the .on() method.
Then, in the callback function, you can reference the form itself with $(this) and use the method find() to locate a child with the name codetext.
And, if you call e.preventDefault(), you cancel the form submission.
My suggestion:
HTML form (can repeat as long as you want):
<form action="post.php" method="POST">
<input maxlength="5" name="codetext" type="text" value="" placeholder="Enter here" />
<input class="button" type="submit" value="SUMBIT" />
</form>
JS:
$(document).ready(function() {
//this way, you can create your forms dynamically (don't know if it's the case)
$(document).on("submit", "form", function(e) {
//find the input element of this form with name 'codetext'
var inputCodeText = $(this).find("input[name='codetext']");
if(inputCodeText.val().length != 5) {
alert('Invalid Entry');
e.preventDefault(); //cancel the default behavior (form submit)
return; //exit the function
}
//when reaches here, that's because all validation is fine
showhidediv('div-info');
//the form will be submited here, but if you don't want this never, just move e.preventDefault() from outside that condition to here; return false will do the trick, too
});
});
Working demo: https://jsfiddle.net/mrlew/8kb9rzvv/
Problem, that you will have multiple id codetext.
You need to change your code like that:
<form action="post.php" method="POST">
<input maxlength="5" name="codetext" type="text" value="" placeholder="Enter here" />
<input class="button" type="submit" value="SUMBIT" />
</form>
<form action="post.php" method="POST">
<input maxlength="5" name="codetext" type="text" value="" placeholder="Enter here" />
<input class="button" type="submit" value="SUMBIT" />
</form>
And your JS:
$(document).ready(function(){
$('form').submit(function(){
var codecheck = $(this).find('input[name=codetext]').val();
if(codecheck.length != 5)
{
alert('Invalid Entry');
} else {
showhidediv('div-info');
}
return false;
})
})

HTML/Javascript form resets automatically

I'm writing javascript that takes in a form and prints it as a "verification" to 'id="printpeople"'. And it works, but after about three seconds, the form refreshes itself, and so does the p tag. The page doesn't seem to refresh itself unless I hit the 'submit' button. Why is this happening?
HTML:
<form name="form" id="form" class="form" onsubmit="createperson()" method="post">
<label for="name">Full Name:</label>
<input type="text" name="name" id="name" /><br>
...
<input type="submit" value="Submit" class="submit" />
</form><br>
<p>People:</p>
<p id="printpeople"></p>
Javascript:
function person(form){
var name = document.forms["form"]["name"].value;//retrieves name field
...
var person = [name,email,gender,address];//creates new person array
return person;
}
function createperson(form){
var personinstance = person(form);
var personstring = "Name "+personinstance[0]+
"\n"+"Email "+personinstance[1]+
...
stringholder(personinstance, "write");
}
window.peoplecriteria = ["Name: ","Email: ","Gender: ","Address: "];
window.peoplearray = []; //stores all the people in here
window.peoplestring = "";//string that's used for pretty printing.
function stringholder(parameter, readwrite){
window.peoplearray.push(parameter);
window.peoplestring += window.peoplecriteria[0]+window.peoplearray[0];
document.getElementById("printpeople").innerHTML = peoplestring;
}
By using:
<form name="form" id="form" class="form" onsubmit="createperson();return false" method="post">
You should prevent the form from submitting itself.
This works by making the submit function return false. By default the onsubmit function returns true. By returning false, you state that you do not want the submission to carry through.
You might be able to stop the form from submitting with the following as your first line in createperson(form):
form.preventDefault();

javascript function in html form

I have seen some other threads like this but they don't seem to help me in my problem. I am new to Javascript and I am struggling to understand which value in the email input has to be called in my javascript function to make it work.
<input type="email" name="myEmail" value="" class="form-control" required placeholder="Please Enter your email" maxlength="50">
The function I am using is this:
function check_v_mail('myEmail') {
fld_value = document.getElementById(field).value;
is_m_valid = 0;
if (fld_value.indexOf('#') >= 1) {
m_valid_dom = fld_value.substr(fld_value.indexOf('#')+1);
if (m_valid_dom.indexOf('#') == -1) {
if (m_valid_dom.indexOf('.') >= 1) {
m_valid_dom_e = m_valid_dom.substr(m_valid_dom.indexOf('.')+1);
if (m_valid_dom_e.length >= 1) {
is_m_valid = 1;
}
}
}
}
if (is_m_valid) {
update_css_class(field, 2);
m_valid_r = 1;
} else {
update_css_class(field, 1);
m_valid_r = 0;
}
return m_valid_r;
}
This function is saved as email_script.js and is called in my footer as follows:
<script src="includes/js/email_script.js"></script>
What am I doing wrong?
You need to call the check_v_mail function. Usually, this is done when the user clicks the button to submit the form.
<form name="myForm" onsubmit="return check_v_mail('myEmail')" method="post">
Email: <input type="email" name="myEmail" value="" class="form-control" required placeholder="Please Enter your email" maxlength="50">
<input type="submit" value="Submit">
</form>
You can add it in form's onsubmit
In addition to calling the function on form submit or field exit, you also need to add id attribute to your element because your function uses getElementById() to get the element but your input element doesn't have id attribute
<input type="email" name="myEmail" id ="myEmail" value="" class="form-control" required placeholder="Please Enter your email" maxlength="50">
To expand on a comment by Mani:
Right now the signature of your function check_v_mail is incorrect, it is written like a call to a function.
Signature in email_script.js could be:
function check_v_mail(emailFieldId) {
fld_value = document.getElementById(emailFieldId).value;
return m_valid_r;
}
Calling on the form could be:
<form onsubmit="return check_v_mail('myEmail');" method="post"></form>
A slight tweak is to have a validate function or class that handles the validation. This can be expanded to call multiple different validation methods and decreases the likelihood that the onsubmit will become complex with additional validations.
<form onsubmit="return validateForm();" method="post"></form>
function validateForm() {
var emailValid = check_v_mail('myEmail')
var firstNameValid = validateFirstName('firstNameInput');
return emailValid && firstNameValid;
}

how to display input text that user has writen in a label

I want to display what the user has witten in an input text. I have to formslike below and on the second form I want to display on a label what the user has witten at the input part. But how can I do this...
The first form:
<form name="password" onsubmit="return Validate()" method="post" id="password" action="#" >
<label for="firstname">*First Name:</label>
<input type="text" name="firstname" id="firstname1" class="textinput" required="required" onchange="firstnamecheck1()"><br>
The second form:
<form name="displaylabel" method="post" id="password" action="#" >
<label>First Name:</label> <label id="l1">li.innerHTML('lastname1')</label><br>
</form>
How can I do this because the inner html I use above li.innerHTML('lastname1') do not give result.
I use this function:
<script>
function doStuff()
{myVar = document.getElementById('lastname1');
document.getElementById('l1').value = myvar;
}
</script>
and this is the part of the form:
<div class="hideformobile" onload="doStuff();">
<form name="displaylabel" method="post" id="password" action="#" >
<label>First Name:</label> <label id="l1"></label><br>
</form>
</div>
But it still it gives no result...What can I do? Please help me
To change the HTML content of an element you may set it's innerHTML property.
document.getElementById('my-element').innerHTML = 'test';
To get/set the value of an <input> element, use it's value property.
document.getElementById('my-input').value = 'something';
You have an onchange function called firstnamecheck1. I don't know what that does, but you can either add the following functionality to that function, or add this to the inline listener:
<input ... onchange="firstnamecheck1(); document.getElementById('l1').innerHTML = this.value;">
However, I'd prefer to set the textContent or innerHTML as appropriate using something like:
setText(document.getElementById('l1'), this.value);
Requires a small helper function to set the text:
function setText(el, text) {
if (typeof el.textContent == 'string') {
el.textContent = text;
} else if (typeof el.innerText == 'string') {
el.innerText = text;
}
}
<label>First Name:</label> <label id="l1">li.innerHTML('lastname1')</label><br>
This is not the proper way to use this javascript. You need to run it inside a function. If you put it in a block like
<script>
function doStuff()
{
document.getElementById('l1').innerHTML = 'lastname1';
}
</script>
When you call doStuff(), that code will execute and change the innerHTML property of the list item element. You can call this sort of function on page or body load as well.
<body onload="doStuff();"> (more content) </body>

Categories

Resources