I've just started programming and I'm at a very basic level, I've just created a form for my student website and I'm trying to validate the Radio Buttons. I know I can just select "checked" in the HTML code but my tutor stipulates it has to be within the JavaScript code. I have researched on here already but the examples many of you have shown haven't worked for me (my fault!) and it just crashes all my previous validations.
Any guidance from all you ninjas is greatly appreciated. Here is a small sample of my code that does work for me as I have deleted the Radio Button validation in frustration, I just want to know how to adapt this code:
<script>
function validate(){
firstname = document.getElementById("txtFirst").value;
errors = "";
if (firstname == ""){
errors += "Please supply a valid First Name \n";
} else if (!firstname.match(/^[a-zA-Z-\s]*$/)){
errors += "Please use only letters in your First Name \n";
}
}
</script>
<body>
<form method="post" action="" class="booking">
<fieldset>
<div>
<label for="txtFirst" class="fixedwidth">First Name</label>
<input type="text" name="txtFirst" id="txtFirst"/>
</div>
<div class="buttonarea">
<input type="submit" value="submit" onclick="validate()"/>
</div>
</fieldset>
</form>
I recommend jQuery for this as you only would need to check $('element').val(). In JavaScript you have to check document.getElementById('element').value. Remember to match both name and id properties for this to work as you can only select one value in a set of radioboxes.
Related
This question already has answers here:
HTML form action and onsubmit issues
(3 answers)
Closed 3 years ago.
i know there are other questions like mine but before you mark it as a duplicate could you please read it.
i am trying to validate my html form using javascript.
i have done this before in another web page and it worked correctly however i am trying to use the same code for my new page but it does not work.
this is the code:
function validateForm(form) {
var valid = true;
if (!form.title.value.length)
{
valid = false;
document.getElementById('titleRequired').style.display = "inline-block";
}
else
{
document.getElementById('titleRequired').style.display = "none";
}
}
<form id="form" action="register.php" method="post" onsubmit="return validateForm(this)">
<h2> create profile: </h2>
<div>
<label for="fname">First Name</label>
<input type="text" id="fname" name="fname" placeholder="Given Name">
<span class="error" id="fNameRequired">first name required</span>
<span class="error" id="capitalRequired">first letter must be capital</span>
</div>
<div>
<input type="submit" value="Submit" name="submit" >
</div>
</form>
i have more inputs for this form however i am doing it step by step and not sure where i am going wrong.
i have this exact same code on another project i worked on with more inputs and it works fine.
the output i am currently getting is: it submits the form as normal even when no text is entered.
You're not returning the result of the validation. Add return valid; before the last curly brace to return false or true so the submit handler knows what to do.
I'm trying to combine the login and register forms on a WooCommerce/WordPress site. The idea is that a single set of fields, username and password, could be submitted by two different forms. The first way I thought of is (simplified for clarity):
<form id="login">
<input id="username">
<input id="password">
<button type="submit">LOG IN</button>
</form>
<form id="register">
<div style="visibility:hidden!important;position:fixed!important;">
<input id="register_username">
<input id="register_password">
</div>
<button type="submit">REGISTER</button>
</form>
Basically, the layout hides the second pair of inputs but shows both buttons. Then, there's some JS that mirrors the values of corresponding fields:
var u = $('#username');
var p = $('#password');
var ru = $('#register_username');
var rp = $('#register_password')
$('#login').on('change blur focus click keyup',function(){
ru.val(u.val());
rp.val(p.val());
});
This seems to trigger a warning that an "invalid field is not focusable" - which I understand - but, can this be solved and done well? Is there a way to do this without JavaScript? Is there a better way altogether?
Let's assume I will show the hidden stuff in the case that there is no JS on the user's browser. Let's also assume I was given this design and asked to implement it, i.e. this is not a question about UX.
Just merge 2 forms into one and set 2 buttons
<form id="login">
<input id="username">
<input id="password">
<button name="submit" type="submit" value="login">LOG IN</button>
<button name="submit" type="submit" value="registration">REGISTER</button>
</form>
After submitting your form you need to check submit value like
if($_POST['submit'] == 'login')
then do code for login
else if($_POST['submit'] == 'registration')
then do code for registration
To reveal the hidden fields in the case of no javascript you would put the data between the following tags:
As far as the fields that are active when there is JavaScript, place that data within the JavaScript itself using document.write("fields here");.
The end result will be that these fields appear when JavaScript is enabled, and do not appear when JavaScript is disabled.
Hope this helps.
I have a form that sends the store the First Name of the user in a database. I was checking the information send by the user using regex in php.
To make my project more interactive, I decided to validate the information jQuery before sending it to PHP.
My Project looks like this:
<script type="text/javascript" src="jquery-2.2.3.min.js"></script>
<script src="http://code.jquery.com/ui/1.9.1/jquery-ui.js" type="text/javascript"></script>
<body>
<form >
<div>
<label>First Name</label>
<input name="firstname" type="text">
</div>
<div>
<input type="submit">
</div>
</form>
</body>
</html>
<script>
$(document).ready(function() {
$("form").submit(function (e) {
var firstname = $(this).find('input[name="firstname"]').val();
var regex = /^[A-Za-z0-9 \-']+$/;//Only numbers, Letters, dashes, apostrophes and spaces are accepted
if(regex.test(firstname)){
alert('Valid Name.');
}else{
alert('Invalid Name.');
e.PreventDefault();
}
});
});
</script>
Now I have 2 questions:
Is it really need to check the First Name in PHP again before storing the data in the database ? (To improve security)
How can I submit the form right after the alert('Valid Name.'); ?
Thanks for providing your help.
First of all have in mind that the validation of users input is implementing at the server side of an application only!!! You can not validate input data at client side with JS because it can be passed very easy(either by disabling javascript or by using tools like Curl).
However you can increase user experience like validate an input before submitting the form or inform the user that forgot to fill in an input.
To inform the user about a not fill in input you can just use the new html 5 attribute required like above
Username: <input type="text" name="usrname" required>
the required attribute will not let the user submit the form unless he had filled the associated input.
Also you can use the maxlength attribute to address a use case like "A password must have X max letters.
Password: <input type="password" name="pass" maxlength="8" size="8"><br>
How to validate input at server side
There are many techniques for this and you can find all of them here at Stackoverflow. Ι will refer the top voted post How can I prevent SQL injection in PHP? which answer exactly your question.
Just two bullets that compact the above post that i suggest you read otherwise
Always escape your data
Use mysqli instead of mysql
How can I submit the form right after the alert('Valid Name.'); ?
this is very easy just use this code
<form action="action_page.php" method="post">
<div>
<label>First Name</label>
<input name="firstname" type="text">
</div>
<div>
<input type="submit">
</div>
</form>
the above code will "send" user's input for process at action_page.php using POST method, where you can read using $_POST supergloba table like $firstname = $_POST['fistsname'] etc.
TRY This
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.15.0/jquery.validate.js" ></script>
<script type="text/javascript" src="jquery-2.2.3.min.js"></script>
<script src="http://code.jquery.com/ui/1.9.1/jquery-ui.js" type="text/javascript"></script>
<body>
<form >
<div>
<label>First Name</label>
<input name="firstname" id="first_name" type="text">
</div>
<div>
<input type="submit">
</div>
</form>
</body>
</html>
<script>
jQuery.validator.addMethod("firstName",function(value,element,param)
{
if(this.optional(element))
{//This is not a 'required' element and the input is empty
return true;
}
if(/^[A-Za-z0-9 \-']+$/.test(value))
{
return true;
}
return false;
},"Please enter a valid First Name");
$(function()
{
$('#myform').validate(
{
rules:
{
first_name:{ required:true, firstName:true }
}
});
});
</script>
Firstly you should ALWAYS validate server side for form submission, especially if you are passing those value along to a DB - SQL injection, the struggle is real.
As for the form submission flow you can...
return true
... after the valid name alert and the form to submit as it normally would.
Since you already have bound to that submit event, It would be even better for the user if you submitted the form via ajax, and providing feedback if the server validation fails. Thus the user never leaves the page and you are able to handle both client and server validation.
Take a look at ParsleyJS - http://parsleyjs.org/ - w00t!
This question already has answers here:
HTML text input allow only numeric input
(78 answers)
Closed 6 years ago.
Trying to limit the user to only enter numbers in a text field.
I am assuming you're talking about FORM in HTML.
There are several ways to do that:
Input type
As Alexander proposed, you can set the input type to number.
For example, in this form the user is required to provide his/her ID number before submitting. Please note that, the type is set to number.
<!DOCTYPE html>
<html>
<body>
<form action="action_page.php">
ID Number:<br>
<input type="number" name="id" value="0">
<br><br>
<input type="submit">
</form>
</body>
</html>
Javascript
you can set a javascript function that validates the input on-submit.
<script>
function validateForm() {
var x = document.forms["myForm"]["id"].value;
if (x == null || x.search(/^\d+$/i) < 0) {
alert("ID must be a number");
return false;
}
}
</script>
<form name="myForm" action="demo_form.php"
onsubmit="return validateForm()" method="post">
ID: <input type="text" name="id">
<input type="submit" value="Submit">
</form>
Here is another example on W3Schools
AngularJS
There is a lot of buzz around AngularJS and I assume you may want to go there in some point.
Fortunately, the AngularJS documents regard that subject are pretty understandable and straightforward or at least to me.
Here are some examples:
Input directive
AngularJS API Ref - input
I wrote a spam filter for a client that rejects submission of forms containing http in a specific field (input).
I am now trying to adapt that for a site which has many forms but also different ID's for each input which are required by other functions.
How should I re-write this code so it applies on any input in a form regardless of field ID?
Html
<form action="#" name="form">
<input type="text" name="txt" id="txt" onblur="validate('txt');"/>
<p id="alert1" style="display:none;"> Please remove the link from this field to continue with the form submission. </p>
<input type="text" name="txt1" id="joso"/>
<input type="submit" id="submit"/>
<p id="alert2" style="display:none;"> Please remove the link from this comments area to continue with the form submission </p>
</form>
Javascript
function validate(id) {
var txtbox = document.getElementById('txt');
var txtvalue = txtbox.value;
txtindex = txtvalue.indexOf('http');
if (txtindex!=-1) {
document.getElementById('alert1').style.display = 'block';
document.getElementById("submit").disabled = true;
} else {
document.getElementById("submit").disabled = false;
document.getElementById('alert1').style.display = 'none';
}
}
Solution performance
For those interested in the solution - it works very well, which is why I want to port it on all my other sites. It cut down 90% of the spam we were getting even though we had another capcha solution installed and it increased the no. of valid requests for offers which we were losing because the capcha solution our CMS was offering were too hard to read. It also performs better than the capcha we were previously using.