Javascript: How to disable submit button until all fields are validated? - javascript

I have several validation functions that work fine and I want to write an additional validation in simple javascript (no jQuery, etc) for the entire form that disables/enables the Submit button depending on whether the other validation functions return true or false. How do I go about that?
For example, for my main HTML I have:
<form id="form" method="POST">
<label class="form">Field 1</label><input type="text" name="input1" onkeyup="validateInput1(); return false">
<label class="form">Field 2</label><input type="text" name="input2" onkeyup="validateInput2(); return false">
...
<button id="submit" type="submit" value="submit">Submit</button>
</form>
For my script I have:
function validateInput1(){
...
}
function validateInput2(){
...
}
Now I want to write a function with something like:
function validateForm(){
var submitButton = document.getElementById('submit');
submitButton.disabled = true;
/*If all other validation functions like validateInput1() returns true then submitButton.disabled = false*/
}
How do I do this?

Start the button off as disabled. Hook to the onchange event for each of the form inputs, and then have it check the validateForm() function to see if all the forms are valid. After that, if they're all valid, set the submit button to enabled, otherwise set it to disabled.
var inputs = document.querySelectorAll('#form input');
var validateInput1 = function()
{
return document.getElementById('input1').value != '';
}
var validateInput2 = function()
{
return document.getElementById('input2').value != '';
}
var validateForm = function() {
if ( !validateInput1() ) {
return false;
}
if ( !validateInput2() ) {
return false;
}
return true;
}
for ( var i = 0, len = inputs.length; i < len; i++ )
{
var checkValid = function() {
document.getElementById('submit').disabled = !validateForm();
//Is the same as:
/*if ( !validateForm() )
{
document.getElementById('submitButton').disabled = true;
}
else
{
document.getElementById('submitButton').disabled = false;
}*/
}
inputs[i].addEventListener('change', checkValid);
inputs[i].addEventListener('keyup', checkValid);
}
<form id="form" method="POST" onsubmit="alert('Submitted!'); return false">
<label class="form">Field 1</label><input type="text" name="input1" id="input1">
<label class="form">Field 2</label><input type="text" name="input2" id="input2">
<button id="submit" type="submit" value="submit" disabled="disabled">Submit</button>
</form>

Related

Why is my form still submitting even though it returns false?

I made this code which submits a form with a name and age field with a submit button. My code looks like this:
function checkForm() {
var name = document.forms["form"]["name"].value;
var age = document.forms["form"]["age"].value;
var regName = /^[A-Z]*[a-z]{3,} $/;
var regAge = /^[\d.*]{1,} $/;
if (name == regName && age == regAge) {
return true;
} else {
return false;
}
}
<form name="form" action="register.php" method="POST" onsubmit="return checkForm()">
<p>Name:</p>
<input type="text" name="name" id="name">
<br>
<p>Age:</p>
<input type="text" name="age" id="age">
<br>
<br>
<button type="submit" name="submit">Submit</button>
</form>
The name should be using only upper case and lower case letters and the age must be numerical and a positive integer.
Supposedly, when I entered the wrong data, the form should not return false but its returning true and sending me through to register.php. Is there something wrong with my code?
Try evaluating regex With pattern.test('stringMethod')
function checkForm(event){
var name = document.forms["form"]["name"].value;
var age = document.forms["form"]["age"].value;
var regName = /^[A-Z]*[a-z]{3,} $/;
var regAge = /^[\d.*]{1,} $/;
if (regName.test(name) && regAge.test(age)){
return true;
} else{
event.preventDefault();
return false;
}
}
Try to add event.preventDefault(); when the data is invalid.
function checkForm(event){
var name = document.forms["form"]["name"].value;
var age = document.forms["form"]["age"].value;
var regName = /^[A-Z]*[a-z]{3,} $/;
var regAge = /^[\d.*]{1,} $/;
if (name == regName && age == regAge){
return true;
} else{
event.preventDefault();
return false;
}
}
Form default behaviour is like that if you are calling a function on submit it will get submit. So you can call the function on button submit.
<button type="submit" name="submit" onsubmit="return checkForm()">Submit</button>

what is the correct way to validate form with javascript

should i put "submit" instead "form_name" in the last block of code? what is the correct way?
thanks!
function check() {
var title = document.getElementById("title");
var content = document.getElementById("content");
if (title == "") {
alert("title is required");
return false;
}
if (content == "") {
alert("content is required");
return false;
}
var submit = document.getElementById("form_name");
submit.submit();
}
this is my form
<form action="#" method="post" id="form_name" name="form_name">
<input type="text" name="title" id="title" />
<textarea name="content" id="content" cols="30" rows="10"></textarea>
<input type="submit" value="Submit" id="submit" name="submit" onclick="return check();"/>
</form>
First you are selecting an element and acting like it is the value
var title = document.getElementById("title"); <-- DOM element
if (title == "") { <-- checking the DOM against a string.
You should be using .value to get what was entered.
Next you are submitting the form.... but you clicked on a submit button inside of the form so that will submit the form. So that is not needed.
function check() {
var title = document.getElementById("title").value;
var content = document.getElementById("content").value;
if (!title.trim().length) {
alert("title is required");
return false;
else if (!content.trim().length) {
alert("content is required");
return false;
}
return true
}
And never name anything submit, it just leads to problems.
In most recent browsers you have more power to use
function myFunction() {
var inpObj = document.getElementById("id1");
if (inpObj.checkValidity() == false) {
document.getElementById("demo").innerHTML = inpObj.validationMessage;
}else{
document.getElementById("demo").innerHTML = "";
}
}
<input id="id1" type="number" min="100" max="300" required>
<button onclick="myFunction()">OK</button>
<p id="demo"></p>
Reference:
https://www.w3schools.com/js/js_validation_api.asp

On submit of a form which submit button was clicked

A validation() function needs to be called whenever a form is submitted which validates the input and based on that returns true or false. But based on two submit buttons there are two validation() functions. Here is an example
<form name="abc" id="abc" method="post" onsubmit="return validate()">
<button type="submit" id="save">Save</button>
<button type="submit" id="edit">Edit</button>
</form>
<script type = "text/javascript">
document.getElementById("save").onclick = function() {
validateSave();
}
document.getElementById("edit").onclick = function() {
validateEdit();
}
function validateSave(){
//do validation
}
function validateEdit(){
//do validation
}
function validate(){
//return true or false based on the validation
}
</script>
So basically I want to use onsubmit="return validate() weather to navigate to next page or remain in the same page. So how to use the onsubmit="return validate() alongwith the respective validation on basis of the button clicked.
Any leads/hint would be appreciated.
Thanks
Do something like this :
HTML :
<form name="abc" id="abc" method="post">
<button type="submit" id="save" onclick="validate(event)">Save</button>
<button type="submit" id="edit" onclick="validate(event)">Edit</button>
</form>
JS :
function validateSave(){
console.log("save");
return false;
}
function validateEdit(){
console.log("edit");
return false;
}
function validate(event){
event.preventDefault();
event.stopPropagation();
var callerId = event.target.id;
var formElement = document.getElementById("abc");
if (callerId === "Save") {
formElement.onsubmit = validateSave(); // Or other value/function
}
else {
formElement.onsubmit = validateEdit(); // Or other value/function
}
formElement.submit();
}
I found a way by declaring a flag variable inside the javascript section
<form name="abc" id="abc" method="post" onsubmit="return validate()">
<button type="submit" id="save">Save</button>
<button type="submit" id="edit">Edit</button>
</form>
<script type = "text/javascript">
var flag="";
document.getElementById("save").onclick = function() {
flag="Save";
}
document.getElementById("edit").onclick = function() {
flag="Edit";
}
function validateSave(){
//do validation
}
function validateEdit(){
//do validation
}
function validate(){
if(flag == "Save"){
if(validateSave()){
return true;
}
else{
return false;
}
}
if(flag == "Edit"){
if(validateEdit()){
return true;
}
else{
return false;
}
}
}
</script>

Textbox value compare before submitting

I want to let my two textboxes be checked before those get submitted.
like
if textbox1 >= textbox2 submit
else show errorlabel and dont submit.
How can i do this?
Provide your onclick handler's implementation to extract the value of the two text boxes, then parse them as an int.
function submitForm() {
var first = parseInt(document.getElementById("first"), 0);
var second = parseInt(document.getElementById("second"), 0);
if(first >= second) {
// ...
return true;
} else {
var hiddenTextBox = document.getElementById("error");
hiddenTextBox.style.visibility = "visible";
return false;
}
}
This assumes you have two elements with id="first" and id="second" respectively, and a hidden element with id="error"
Try it like,
$('#submitId').on('click',function(){
if $('#textbox1').val() < $('#textbox2').val()){
$('#erroLabel').show(); // showing error label
return false; // to prevent submitting form
}
});
You can make function in javascript,
<script type="text/javascript">
function checkValues()
{
var searchtext1 = document.getElementById("textbox1").value;
if(searchtext1=='')
{
alert('Enter any character');
return false;
}
var searchtext2 = document.getElementById("textbox2").value;
if(searchtext2=='')
{
alert('Enter any character');
return false;
}
}
</script>
and then in html form
<form method='GET' onSubmit="return checkValues();">
<input type="text" id= "textbox1" name="textbox1" class='textbox' >
<input type="text" id= "textbox2" name="textbox2" class='textbox' >
<input type="submit" id='submit' value="Search" class ='button' >
</form>

Validate a form depending on which submit button is used

So, I have this code
<script>
function validate(f) {
var ok = true;
if (f.id.value === '' || f.id.value === null) {
ok = false;
}
return ok;
}
function validate2(f) {
var ok = true;
if (f.name.value === '' || f.name.value === null) {
ok = false;
}
return ok;
}
</script>
<form action="#" method="post">
<input type="text" name="id"/>
<input type="text" name="name"/>
<input type="submit" name="send_id" value="Send ID"/>
<input type="submit" name="send_name" value="Send Name"/>
</form>
How can I do it to validate the form depending on which submit is used?
I want to execute validate(); if the Send Id button is clicked and validate2() if we use the other one.
You can do this:
<form id="myForm" action="#" method="post">
<input type="text" name="id"/>
<input type="text" name="name"/>
<input type="submit" name="send_id" value="Send ID" onclick="return validate();" />
<input type="submit" name="send_name" value="Send Name" onclick="return validate2();" />
</form>
This way when your functions return false (meaning the form is not valid) the submit is interrupted.
And get your f parameter manually.
function getForm() {
return document.getElementById("myForm");
}
function validate() {
var f = getForm();
var ok = true;
if (f.id.value === '' || f.id.value === null) {
ok = false;
}
return ok;
}
function validate2() {
var f = getForm();
var ok = true;
if (f.name.value === '' || f.name.value === null) {
ok = false;
}
return ok;
}
You have to give an id to your form as show above.
Have another function as checkValidate() or something as you like and check it on click of both the buttons
<script>
function checkValidate(buttonName) {
if(buttonName == 'send_id'){
return validate();
}else{
return validate2();
}
}
function validate() {
var ok = true;
if (f.id.value === '' || f.id.value === null) {
ok = false;
}
return ok;
}
function validate2() {
var ok = true;
if (f.name.value === '' || f.name.value === null) {
ok = false;
}
return ok;
}
</script>
<form action="#" method="post">
<input type="text" name="id"/>
<input type="text" name="name"/>
<input type="submit" name="send_id" value="Send ID" onclick="return checkValidate(this.name)"/>
<input type="submit" name="send_name" value="Send Name" onclick="return checkValidate(this.name)"/>
</form>
I hope it helps...
Not tested.. but something like that...
$( "input[name='send_id']" ).click(function(event) {
event.preventDefault()
validate();
$("form").submit();
});
$( "input[name='send_name']" ).click(function(event) {
event.preventDefault()
validate2();
$("form").submit();
});

Categories

Resources