Validation and form action dont work together - javascript

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.

Related

How to recheck required input fields in JavaScript/HTML5

I'm trying to stay away from JQuery for this one (nothing against JQuery, I just don't want to load a huge library into this project for something small like this).
I'm curious how I might tell HTML5 to recheck all the required input fields in a given form. For example, I have this form (albeit slightly more complicated but you get the point):
<form action="here" onsubmit="check()">
<input required name="something">
<input type="submit">
</form>
If I don't have anything in that required field, HTML5 shows a popup error, something to the effect of "Please fill in this required field". What is stopping the user from putting in a single space, or some nonsense character like % or >? I'd like to partially validate this client-side (in addition to server side) so it isn't particularly inconvenient when the page redirects to the form submission page and then shows the error, and then goes back to the form, prompting the user to enter everything over again.
Assuming in my onsubmit function check I've removed all whitespace and/or nonsense characters from the ends of the string, how can that function then tell HTML5 to recheck the form to see if the required fields are still not empty?
Instead of onsubmit="check()" use addEventListener.
Now you can do everything with input data.
document.getElementById("submit").addEventListener("click", function(event){
var something = document.getElementById("something").value;
document.getElementById("something").value = something.replace(/[^A-Z0-9]/ig, "");
});
<form action="here">
<input required name="something" id="something">
<input type="submit" id="submit">
</form>
try to use regexp pattern (e.g. exclude white chars: [^\s]*, allow only letters [A-Za-z]*, ...)
<form action="here" onsubmit="check()">
<input required pattern="[^\s]*" name="something" >
<input type="submit">
</form>

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

Bypass HTML "required" attribute when submitting [duplicate]

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>

Form action affects only the form itself

I'm working on a single PHP file, which has 2 different forms.
Example:
<form action="index.php" method="POST">
<input type="checkbox" name="box1">
<input type="submit" value="submit1" name="submit">
</form>
<br>
<form action="index.php" method="POST">
<input type="checkbox" name="box2">
<input type="submit" value="submit2" name="submit">
</form>
My problem is, I want to make both of them work at the same time, independent from each other. For example, when I hit 'submit1', the whole index.php reloads since action is set to that page. The other checkbox might lose it's condition, if I set it to checked before submitting the first form. Might be confusing, I know.. Since I have PHP code behind, I can' really handle the whole thing between 1 form tag. That's why I'm asking if there's another option like javascript, or something. Thanks in advance!
You can use a javascript cookie. You could set it so the cookie will have the fields and values of everything in both forms, and then is saved/created upon submit. Then once the page is reloaded, javascript can split the cookie and refill the field values for the other form. You might need a hidden field in both forms so that you can identify which form was submitted. Here's a tutorial that might explain cookies to you in greater detail: http://www.tutorialspoint.com/javascript/javascript_cookies.htm

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