Bypass HTML "required" attribute when submitting [duplicate] - javascript

This question already has answers here:
Required attribute HTML5
(7 answers)
Closed 9 years ago.
I use required for a 1st check before submitting a form.
<form action="myform.php">
Foo: <input type="text" name="someField" required="required">
<input type="submit" value="submit">
<input type="submit" value="ignore">
</form>
Problem is, that I have an "ignore" button, which submits the form as well and the backend logic then sets a correct state in a DB. In this case (ignore) the validation is not desired (because there is no need to fill in field "Foo").
What's the best way to handle the 2 scenarios?
I am aware that I could give up "required" and do the validation somewhere else (backend / JavaScript). I am looking for a way to keep the "required".
I could use some Js onclick for the ignore button scenario and remove the attribute just before sending the form ( https://stackoverflow.com/a/13951500/356726 ).
But actually I am looking for something smarter ....
--- Edit ---
Yes, duplicate of Required attribute HTML5

No JavaScript, no second form needed, and the validation can stay:
For exactly this use case the HTML5 spec has designed the formnovalidate attribute for submit elements (like <input type=submit>), as one of the attributes for form submission:
The formnovalidate attribute can be used to make submit buttons that do not trigger the constraint validation.
So simply put
<form action="myform.php">
Foo: <input type="text" name="someField" required>
<input type="submit" value="submit">
<input type="submit" value="ignore" formnovalidate>
</form>

Your #2 is a common approach. Something like:
$('input[value="ignore"]').click(function() {
$(this).siblings('input[type="text"]').removeAttr('required');
});
Might have to use mousedown to beat submit.

If you don't want to use Javascript, you could make them separate forms and have all the inputs set to hidden for the ignore form.
Not the best option, but it is an alternative.

You should use approach #1 on the following grounds: The main reasons for using required instead of JavaScript validation is that it is simpler and it works even when JavaScript is disabled. Here the simplicity does not apply, since the use of required makes things more difficult. And the latter reason does not apply either: with JavaScript disabled and the browser supporting required, the “ignore” button does not work unless some data is entered in the textfield.
Another alternative is the one mentioned on #MattKenefick’s answer. It might even result in simpler structure and logic. If the form is really as simple as in the example, it is straightforward to split it to two forms:
<form action="myform.php">
Foo: <input type="text" name="someField" required="required">
<input type="submit" value="submit">
</form>
<form action="myform.php">
<input type="submit" value="ignore">
</form>

Related

Validation and form action dont work together

I have a form with validation on data (E.g the mobile number must contain 10 numbers and numeric) . once everything submitted i've pressed submit button then those data must send to the data base over the php file (access from from action=file.php)
im not sure if i type this form part correctly or not
please help
<form action="patientdetails.php" method="POST" name='registration' onSubmit="return formValidation()"/>
<input type="image" src="Images/submit.png" alt="Submit" name="submit" value="Submit" />
You can use code like this for form validation :
`<script>` <br>
`function formValidation(){`<br>
`var myform=document.registration;`<br>
`var num=myform.mobilenum.value;`<br>
`if(num<10){`<br>
`alert("invalid number");`<br>
`return false;`<br>
`}`<br>
`else{`<br>
`return true;`<br>
`}`<br>
`}`
`</script>`
`<form action="patientdetails.php" method="POST" name='registration' onSubmit="return formValidation()"/>`<br>
`<input type="number" name="mobilenum" />`<br>
`<input type="submit" name="submit" value="Submit" />`
Nothing in your form code will cause a problem with validating your input.
Not having any <input> elements does make it impossible for anyone to type the mobile number though.
There are some things which are wrong, out of date, or low quality…
There is no name attribute for form elements
Intrinsic event attributes like onsubmit are better replaced by JavaScript that uses addEventListener
Image type inputs are designed to provide server side image maps, if you just want a graphic to be your submit button you should probably have <button><img></button> instead
… but none would cause the problem you are describing.

append required input into existing form

I've got a small-big problem with ajax. Let's describe the situation:
I've got a form with submit=javascript:function()
function will call AJAX with some values, and on success I want to append some content with 'required' input to existing form.
I was trying many things, most from: How to set HTML5 required attribute in Javascript? , but still cannot reach it.
example code:
<form id="myFormID" action="javascript:mycustomsubmit()">
<input type="text" id="add" style="margin:2px;" required>
<input type="submit" name="add" value="Add" class="btn btn-primary">
<textarea rows="5" id="custom_add"></textarea>
(...) on ajax success clear form values and insert new required input:
$("#add").val('');
$("#add").after('<input name="anotherinput" type="text" required>');
so after this my html code looks like this:
<form id="myFormID" action="javascript:mycustomsubmit()">
<input type="text" id="add" style="margin:2px;" required>
<input name="anotherinput" type="text" required="">
<input type="submit" name="add" value="Add" class="btn btn-primary">
<textarea rows="5" id="custom_add"></textarea>
</form>
And in fact it is (with this difference, that new input has required=""), but this new input is not required at all - I can send form even if this input is empty. I was trying to do it by append required, required="required", required=true, required="true", by append just input and then jQuery .prop or/and .attr, by JS examples from link - but it is still not working.
2nd question: After ajax append content and clear values I've got red border around required input field - is there any simple way to remove it (but to show this border and info if user will try to send form with this input empty) in FF,Chrome,IE ?
First post here...
Thanks in advance for any advices!
edit:
what is interesting: when I've submitted my form few times (so I've got few input fields) and I executed $("input").attr('required',true).prop('required', false); then obviously form haven't got any required inputs. However when I've executed it with prop "true" then only original input is really required, all added by append still can be empty...
This is a question consisting of multiple questions. So I'll try to identify and answer them separately.
How to append a new input field after your input field with ID "add" on submitting the form?
Try this instead (your selector was wrong):
$("#add").val('');
$("#add").after('<input name="anotherinput" type="text" required>');
How do I get rid of the red border?
I suggest that you use jQuery to handle the form submit (not tested):
$('#myFormID').submit(function(e) {
// Checking if all required fields are filled out.
if (!e.target.checkValidity()) {
// TODO: Not all required fields are filled out. Do something e.g. adding your new input field?
// Preventing form submit to continue. I think this should prevent the red border. Not tested though...
e.preventDefault();
}
else {
// Everything is OK. Do whatever is needed.
}
});
I'm not sure if I got your questions, but I hope it helps.
Try this,
$("input").attr('required',true);
or
$("#name_add").attr('required',true);

How to check inputs in <form> and send form correctly

I have 2 questions:
How to check input better? I have idea:
First, make field near input.
<input type='text' name='firstname'><label id='firstnameError'></label>
Second, call js-function on input onBlur with id of input and id of this label.
<input type='text' name='firstname' id='firstname' onBlur='checkEmpty("firstname", "firstnameError");'><label id='firstnameError'></label>
And js-script:
function checkEmpty(fieldId, errorFieldId)
{
var data = document.getElementById(fieldId).value;
if (data == "")
{
document.getElementById(errorFieldId).innerHTML="Error, input something!...";
}
}
And I will just use this function on all inputs, right?
Is it correct?
How to check all inputs in form correctly?
Sure I can set type=button and onSubmit call some function, which will check all elements in this form. ~ Same function like in first question, but with 5-7 if-blocks for each input. And yes for 10 forms, I will have to write 10 functions, etc. How better do it? Seems to me, I can only send form Id/name and get childs of element. Am I correct?
Maybe another way? I use jquery on my site anyway (some ajax). Maybe it is easier to do what I want on jquery? The problem is I am not too good in js, to use jquery easily. What do you think?
If you just want to verify if some data is provided or not, you can use required attribute.
<input type="text" name="username" required>
if you are using XHTML it should be as shown below..
<input type="text" name="username" required="required">
The required attribute is supported in Internet Explorer 10, Firefox, Opera, and Chrome and is not supported in Internet Explorer 9 and earlier versions, or in Safari.
In case if you want to use JavaScript. You can create a javascript function which will be called on submit of the form.
<form name="search" onsubmit="return validate()" >
Name: <input type="text" name="name"/>
Age: <input type="gender" name="sex"/>
<input type="submit" name="Submit" value="Submit"/>
</form>
function validate(){
// all the code for verification
return false; // if any of the step verification step fails. Otherwise return true.
}
Source: http://www.w3schools.com/tags/att_input_required.asp
To improve on your design, it's better to use non-inline JavaScript. Try using a design like this:
var fname = document.getElementById("firstname");
var other = document.getElementById("otherid");
fname.onblur = other.onblur = function() {
checkEmpty(this.id,this.id+"Error");
}
This will give all your desired elements the same onclick function and eliminate those pesky onblur attributes.
Edit: make sure your variables are declared before you chain assignments like this, or you will yield unwanted global variables.

What is jQuery Unobtrusive Validation?

I know what the jQuery Validation plugin is. I know the jQuery Unobtrusive Validation library was made by Microsoft and is included in the ASP.NET MVC framework. But I cannot find a single online source that explains what it is. What is the difference between the standard jQuery Validation library and the "unobtrusive" version?
Brad Wilson has a couple great articles on unobtrusive validation and unobtrusive ajax.
It is also shown very nicely in this Pluralsight video in the section on " AJAX and JavaScript".
Basically, it is simply Javascript validation that doesn't pollute your source code with its own validation code. This is done by making use of data- attributes in HTML.
With the unobtrusive way:
You don't have to call the validate() method.
You specify requirements using data attributes (data-val, data-val-required, etc.)
Jquery Validate Example:
<input type="text" name="email" class="required">
<script>
$(function () {
$("form").validate();
});
</script>
Jquery Validate Unobtrusive Example:
<input type="text" name="email" data-val="true"
data-val-required="This field is required.">
<div class="validation-summary-valid" data-valmsg-summary="true">
<ul><li style="display:none"></li></ul>
</div>
For clarification, here is a more detailed example demonstrating Form Validation using jQuery Validation Unobtrusive.
Both use the following JavaScript with jQuery:
$("#commentForm").validate({
submitHandler: function(form) {
// some other code
// maybe disabling submit button
// then:
alert("This is a valid form!");
// form.submit();
}
});
The main differences between the two plugins are the attributes used for each approach.
jQuery Validation
Simply use the following attributes:
Set required if required
Set type for proper formatting (email, etc.)
Set other attributes such as size (min length, etc.)
Here's the form...
<form id="commentForm">
<label for="form-name">Name (required, at least 2 characters)</label>
<input id="form-name" type="text" name="form-name" class="form-control" minlength="2" required>
<input type="submit" value="Submit">
</form>
jQuery Validation Unobtrusive
The following data attributes are needed:
data-msg-required="This is required."
data-rule-required="true/false"
Here's the form...
<form id="commentForm">
<label for="form-x-name">Name (required, at least 2 characters)</label>
<input id="form-x-name" type="text" name="name" minlength="2" class="form-control" data-msg-required="Name is required." data-rule-required="true">
<input type="submit" value="Submit">
</form>
Based on either of these examples, if the form fields that are required have been filled, and they meet the additional attribute criteria, then a message will pop up notifying that all form fields are validated. Otherwise, there will be text near the offending form fields that indicates the error.
References:
- jQuery Validation: https://jqueryvalidation.org/documentation/
jQuery Validation Unobtrusive Native is a collection of ASP.Net MVC HTML helper extensions.
These make use of jQuery Validation's native support for validation driven by HTML 5 data attributes.
Microsoft shipped jquery.validate.unobtrusive.js back with MVC 3.
It provided a way to apply data model validations to the client side using a combination of jQuery Validation and HTML 5 data attributes
(that's the "unobtrusive" part).

How send a form with Javascript when input name is "submit"?

Question: How can you send a form with Javascript if one form input has the name submit?
Background: I am redirecting the user to another page with a hidden HTML form. I cannot change name on the (hidden) inputs, since the other page is on another server and the inputs need to be exactly as they are. My HTML form looks like this:
<form id="redirectForm" method="post" action="http://www.example.com/">
<input name="search" type="hidden" value="search for this" />
<input name="submit" type="hidden" value="search now" />
</form>
I use the following javascript line to send the form automatically today:
document.getElementById('redirectForm').submit();
However, since the name of one input is "submit" (it cannot be something else, or the other server won't handle the request), document.getElementById('redirectForm').submit refers to the input as it overrides the form function submit().
The error message in Firefox is: Error: document.getElementById("requestform").submit is not a function. Similar error message in Safari.
Worth noting: It's often a lot easier to just change the input name to something other than "submit". Please use the solution below only if that's really not possible.
You need to get the submit function from a different form:
document.createElement('form').submit.call(document.getElementById('redirectForm'));
If you have already another <form> tag, you can use it instead of creating another one.
Use submit() method from HTMLFormElement.prototype:
HTMLFormElement.prototype.submit.call(document.getElementById('redirectForm'));

Categories