<html>
<head>
</head>
<body>
<form class="form-horizontal cmxform" id="validateForm" method="get" action="../../course_controller" autocomplete="off">
<input type="text" id="course_name" name="course_name" placeholder="Enter Course Name..." class="row-fluid" required onkeyup="javaScript:validate_course_name();">
<label id="course_name_info" style="color:rgba(255,255,255,0.6);font-size:13px">
</label>
<button type="submit" name="user_action" value="add" class="btn btn-primary" onClick="javaScript:validate();" >Save</button>
<button type="reset" class="btn btn-secondary">Cancel</button>
</form>
<script type="text/javascript">
/**** Specific JS for this page ****/
//Validation things
function validate_course_name(){
var TCode = document.getElementById('course_name').value;
if( /[^a-zA-Z1-9 _-]/.test( TCode ) ) {
course_name_info.innerHTML="Please Enter Only Alphanumeric or _,-,' ' ";
return false;
}
else
{
course_name_info.innerHTML=" ";
return true;
}
}
function validate(){
validate_course_name();
}
</script>
</body>
</html>
So this the code ...I am applying alpha numeric validation on one field but even if i give invalid input like some other characters the form is getting submitted where am i doing it wrong?
i am very new to this web so any help will be appreciated:)
There are several issues here. First, you are never returning the result, so even if the function results in false, it is not returned to the form so the form goes on its merry way. To fix, you can add an onsubmit to the form tag, or even better attach an onsubmit event to the form.
onsubmit="return validate();"
Second, you only need the one function, calling a function from another function is not necessary here, and results in an additional level of difficulty since you will need to return the result to the wrapper function, which will then need to return that result to the form.
//Validation things
function validate() {
var TCode = document.getElementById('course_name').value;
if (/[^a-zA-Z1-9 _-]/.test(TCode)) {
course_name_info.innerHTML = "Please Enter Only Alphanumeric or _,-,' ' ";
return false;
} else {
course_name_info.innerHTML = " ";
return true;
}
}
Here is a working fiddle of your example: http://jsfiddle.net/duffmaster33/nCKhH/
Your validate() function should return the result of the validation. Currently the result of validate_course_name is discarded. In other words, it should look something like this
function validate(){
return validate_course_name();
}
Also you might want to move the validation to
<form onsubmit="return validate()" ...
You need to wrap course_name_info with a getElementById
document.getElementById('course_name_info').innerHTML="Please Enter Only Alphanumeric or _,-,' ' ";
and then change the style of the label so the font isn't white on white background.
Hope that fixes it.
Related
<form action="#" method="post" id="book-list">
<div class="form-group">
<label for="email">Email</label>
<input type="text" id="email" class="form-control">
</div>
<input type="submit" value="Add" class="btn btn-primary btn-block">
</form>
<script type="text/javascript">
function isEmail(email){
return /^([A-Za-z0-9_\-\.])+\#([A-Za-z0-9_\-\.])+\.([A-Za-z](2,4))$/.test(email);
}
const form = document.querySelector('#book-list').addEventListener('submit',(e) =>{
e.preventDefault();
const inputEmail = document.querySelector('#email').value;
if(isEmail(inputEmail) === false ){
console.log('you lost');
document.querySelector('#email').focus();
return false;
}else{
console.log('you win');
return true
}
});
</script>
Playing around with this email validation, is there anything wrong
with the code? even I filled the field with the proper email address like myname#gmail.com it kept
printing you lost result instead of printing the you win, is it because the form submit?
You can use input type='email' if you want to allow html5 to do the validation for you, the submit wont fire if the field is not valid.
Otherwise you can change your regexp a bit to the below one
([A-Za-z0-9_\-\.])+\#([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})
The problem with your regular expression is the syntax for 2 to 4 characters.
Instead of (2,4) it should be {2,4}
function isEmail(email){
return /^([A-Za-z0-9_\-\.])+\#([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/.test(email);
}
isEmail('email#example.com')
// true
However, you may want to just use HTML's built in email type for your input. This will probably be more reliable than any regular expression you could could craft.
Your regular expression in the function isEmail is not correct. Change it to this
function isEmail(email){
return /^([a-zA-Z0-9._-]+#[a-zA-Z0-9._-]+\.[a-zA-Z0-9_-]+)$/.test(email);
}
Then you will get the right response when you submit with a valid email.
I'm trying to do a form and while the alert is popping up it is still submitting. How do I get it to stop submitting??
function validate() {
var first = document.register.first.value;
if (first == "") {
alert("please enter your name");
first.focus();
return false;
}
return (true);
}
<body>
<form name="register" action="testform.php" onsubmit="return(validate());">
<input type="text" name="first" />
<button type="submit" />Submit
</form>
</body>
You added the parenthesis on return() then return(validate()) which we use () when calling the function so it might be considering return a custom function which returns undefined and when returned the undefined it ignores and continue the execution.
How ever the validate is called but it's response is not returned to the form.
Fixed version:
<head>
<script>
function validate(e) {
var first = document.register.first.value;
console.log(document.register.first)
if( first == "" ) {
alert( "please enter your name" ) ;
return false;
}
return(true);
}
</script>
</head>
<body>
<form name="register" action="testform.php" onsubmit="return validate()">
<input type="text" name="first" />
<button type="submit" >sbmit</button>
</form>
</body>
You are better of using the required attribute on the front end of things. It will 'force' the user to input text into the input field before it is able to submit. Please note that I put quotation marks around the word 'force', because one can just edit the HTML and circumvent the HTML required attribute. Therefore make absolutely sure that you are validating user input on the PHP side as well.
Many tutorials and examples exist for PHP Form Validation, such as this one from W3Schools and this one from Medium.
<form name="register" action="testform.php">
<input type="text" name="first" required/>
<input type="submit" value="Submit"/>
</form>
You have several bugs in your code.
<button> element is not self-closing
you are calling focus on value of the input instead of the input element which throws exception
function validate() {
var input = document.register.first;
var text = input.value;
if( text == "" ) {
alert( "please enter your name" ) ;
input.focus();
return false;
}
return true;
}
I think the issue is with the button's type="submit". Try changing it to type="button", with an onclick function that submits your form if validate() returns true.
edit: Arjan makes a good point, and you should use required. But this answers why the form was submitting.
I am brand new to Javascript and am just using it to make a simple website for fun. I have tried searching the web but am still stuck, so if you could help me or redirect me towards other help, that would be great.
I am trying to use Javascript to send a user to another html page in my site if their input matches my criteria. So I wanted to use an if/else statement to do this: if the text input equals ODQHVHMJKD, it would send them to page3.html. However when I try this on the browser, nothing happens--it just takes me to an identical page with ?codebox1=f&button1=Submit at the end of the address.
Here is my script section:
<script type="text/javascript">
function testResults (form) {
if (form.codebox1.value == ODQHVHMJKD) {
window.location.pathname = 'page3.html';
}
else {
window.alert("Try again!");
}
};
</script>
Here are my form elements:
<form name="form1" method="GET">
<input name="codebox1" type="text" />
<input name="button1" type="submit" value="Submit" onClick="testResults(this.form)"/>
</form>
Can you help me so that I can get this to work? It's more than likely I've done everything completely wrong--any help is appreciated!
Try this,
function testResults (form) {
if (form.codebox1.value == "ODQHVHMJKD") {
window.location = 'page3.html';
}
else {
window.alert("Try again!");
}
return false;
};
You need to prevent the default action of the form. In the submit event, call e.preventDefault(); or return false In addition, you need quotation marks around ODQHVHMJKD
Js Fiddle: http://jsfiddle.net/prankol57/Ht45t/
Maybe this can help you.
<form name="form" onsubmit="Results()">
<input type="text" name="fname" id="val">
<input type="submit" value="Submit">
</form>
<script type="text/javascript">
function Results() {
var val = document.getElementById('val').value;
if (val == "ODQHVHMJKD") {
window.location = 'page3.html';
} else {
window.alert("Try again!");
}
};
</script>
I'm sure I must have missed something really obvious, but can't for the life of me see what it is.
I have the below javascript, that (in theory) looks at the form when I click submit, and tells me if I have left the 'RefNo' field blank (in the final form there will be various fields to check, so I have used class='required' to identify them all). But so far, when I click submit, nothing happens (except the form is submitted with the missing data).
I've tried various options that I have found on the internet, and this seemed the most promising.
If anyone can see what I have done wrong it would be really appreciated.
<html>
<head>
<script language="JavaScript" src="jquery.js" type="text/javascript"></script>
<script type="text/javascript">
function submitForm()
{
$("#Form1").submit(function()
{
$('.required input').each(function()
{
if ($(this).val() == '')
{
$(this).addClass('highlight');
}
}
);
if ($('.required input').hasClass('highlight'))
{
alert("Please fill in a Ref Number and try again");
return false;
}
}
);
}
</script>
</head>
<body>
<form method="POST" action="test9.php" name="Form1" ID="Form1">
<input TYPE="text" ID="RefNo" NAME="RefNo" VALUE="" size="25px" class="required"></input>
</br>
<p>
<input type="submit" Name="submit" id="submitButton" value="Report History" onClick='submitForm()'></input>
</p>
</form>
</body>
Your selectors should be $('input.required'), not $('.required input').
First, I think you should use Jquery validation plugin.
Ohterwise, this code should work :
-add a onsubmit="return submitForm()" in your Form tag
<form method="POST" action="test9.php" name="Form1" ID="Form1" onsubmit="return submitForm();">
-get rid of the onclick on the submit button
-and here is the submitForm function :
function submitForm() {
var valid = true;
$('input[class="required"]').each(function() {
if ($(this).val() === '') {
alert("One field is empty and try again");
valid = false;
}
});
return valid;
}
But I really recommend jquery.validate.js
Your selector appears to be a bit off:
It should be $('.required')
The way you have it tries to select an input nested inside a Required class.
Instead of doing it on form submit, remove the submit input type from the button and just have it be a regular button.
With that in mind, your javascript should be:
<script>
$('#submitButton').click(function () {
$('input.required').each(function() {
if ($(this).val() == '') {
$(this).addClass('highlight');
}
});
if ($('.highlight').length > 0) {
alert("Please fill in a Ref Number and try again");
return false;
}
else {
$('#Form1').submit();
}
});
</script>
Otherwise, the way that you're doing it, you would have to cancel the event until you run your check for missing data, and then submit the form anyway. This way keeps you from having to cancel the action, as older IE browsers do that differently than the other browsers, and even newer versions of IE. So it makes your code more readable.
The selector should be either $('input.required') or $('#RefNo').
$('#RefNo') is more faster since it uses native getElementById method.
I have a check box in my registration form like this:
<form name="reg" id="reg" method="post">
<input type="checkbox" onclick="return validate('tos')" name="tos"/>
</form>
And I am using JS to check if its ticked, and if so, display a green tick in the form. However, its not actually ticking the check box when its clicked but it is loading the green tick.
Additionally, clicking it a second time doesn't remove the green tick which it should, because the user effectively unticked the check box.
So my JS is this:
function validate (type){
output = [];
var x = document.getElementById("reg");
if (type == 'tos'){
div = 'result_tos';
input = x.elements[4].checked;
if (input){
output.push('<img src="correct.png"/>');
} else {
output.push('You must agree to our terms of service in order to join !');
}
document.getElementById(div).innerHTML = (output.join('')); //display result
}
}
The following jsfiddle is a slightly modified version of your code that seems to be working fine. I don't think your error is here. (I'm not familiar with elements; is that IE specific? I changed that to work on other browsers.)
http://jsfiddle.net/QnDAg/1/
I would approach this as below. Pass a reference to the element from the listener.
<form name="reg" id="reg" method="post">
<input type="checkbox" onclick="return validate(this)" name="tos">
</form>
<script type="text/javascript">
function validate(el) {
// you don't really need a reference to the form,
// but here's how to get it from the element
var form = el.form;
if (el.name == 'tos') {
if (el.checked) {
// show pass graphic (green tick?)
} else {
// hide checkbox and show text
}
}
}
</script>
Swapping between displaying the tick and text should be done by setting a class value, that way you can change it to whatever you want in the markup and the script just toggles the two.
This is probably how I would suggest you do this, which is more complex than the example given, but I'm struggling a little bit with the intended flow and the flow the OP is using:
Mock HTML
<form name="reg" id="reg" method="post">
<input type="checkbox" id="agree" name="agree"/> Agreement<br/>
<input type="checkbox" id="ok" name="ok"/> Ok<br/>
<input type="checkbox" id="tos" name="tos"/> TOS<br/>
<button name="submit" type="submit">Submit Validation</button>
</form>
<h1>Display Output</h1>
<div id="display"></div>
Iterating Validation
function validate (){
var display = document.getElementById('display'),
output = [],
checks = ['agree','ok','tos'],
check,
msg;
while (check = document.reg[checks.pop()]) {
if (!check.checked) {
switch (check.name) {
case 'agree':
msg = 'You must AGREE!';
break;
case 'ok':
msg = 'You must OK!';
break;
case 'tos':
msg = 'You must TOS!';
break;
}
output.push(msg);
}
}
if (output.length == 0) {
output = [
'You have successfully validated!',
'<img src="http://goo.gl/UohAz"/>'
];
}
display.innerHTML = output.join('<br>');
return false;
}
And don't forget the window.onload when you attach the event handler. Below isn't necessarily the preferred preferred method, but it's cleaner than inline handlers like onclick="validate()".
window.onload = function(){
document.reg.onsubmit = validate;
};
http://jsfiddle.net/bj5rj/2