I wrote an HTML code in which i'm validating the text field for alphabetical value Regex=/^[a-zA-Z]*$/. Actually for invalid input I want that form should not get submitted.
Validation Code
function Validate() {
var fname=$("#fname").val();
if(!(fname.match(Regex)))
alert("Invalid First Name");
return false;
}
HTML Code
<input type="text" name="fname" id="fname" onblur="return Validate();"/>
What should I do, so that for invalid value form should not get submitted.
It looks like you have to return false in onsubmit handler. onblur just handles focus.
Try to change onblur -> onsubmit
Use the onsubmit event of the form element to return true when validation was ok or false if any field did not validate.
Here is a working example. It also demonstrates that you should not rely on client sided validation since nobody stops you from doing the get (or even post) request anyway by just typing in the url. You have been warned about the limitations of client sided validation so here is the code:
<html>
<head>
<script>
function Validate() {
var text = document.getElementById("fname").value;
// simple validation example
if (text != "secret") {
alert("you must enter the right secret string!");
return false;
}
// everything validated
return true;
}
</script>
</head>
<body>
<form name="myForm" method="get" onsubmit="return Validate();">
<input type="text" name="fname" id="fname"/>
</form>
</body>
</html>
Related
I'm trying to create a super simple email validator by using a regular expression. I've checked out similar questions here on SO as well as looking up other solutions elsewhere, like W3resource. I'm not sure if I'm overlooking something or if I have something typed wrong. The problem I'm having is that whether I enter either a correct or incorrect email, nothing happens. Neither of my alerts are working and the page remains blank.
Here is my Javascript code.
function checkmail(inputText)
{
var emailregex = /^\w[-._\w]*\w#\w[._\w]*\w\.\w{2,8}$/;
if(inputText.value.match(emailregex)) {
alert("You have entered a valid email address!");
return true;
} else {
alert("You have entered an invalid email address!");
return false;
}
}
Here is my relevant HTML code.
<div class="mail">
<center>
<p>Please enter an email address.</p>
<form id="inputemail">
<input type='text' name='input'/>
<input type="submit" name="submit" value="Verify" onclick="checkmail(inputText)"/>
</form>
</center>
</div>
<script src="regexobj.js"></script>
</body>
</html>
You need to specify where to get the data from. In your code you have a function that defines a variable "inputText". In your code there is no data being sent to the function and the function fails to get the data and returns an error.
To fix this you need to specify the data that you want to get, for example:
function checkmail(){
var input = document.querySelector("input[name='input']");
var emailregex = /^\w[-._\w]*\w#\w[._\w]*\w\.\w{2,8}$/;
if(input.value.match(emailregex)) {
alert("You have entered a valid email address!");
return true;
} else {
alert("You have entered an invalid email address!");
return false;
}
}
In this example the function will search for an input field with the name of input. input.value will contain the data from the input field.
In your HTML file you need to change the button submit to
<input type="submit" name="submit" value="Verify" onclick="checkmail()"/>
I have tested the above code and it should work accordingly. I hope to have helped with your problem.
Edit:
When submitting the form the page will automatically reload, if you want to stay on the same page and just give an alert you could do the following changes in your HTML file:
Remove the onsubmit property on the Submit button
<input type="submit" name="submit" value="Verify"/>
Add the following onsubmit function to your form
onsubmit="event.preventDefault(); checkmail();"
When you submit the form, the form will first prevent the page from reloading and will then execute your function. When you click on the alert, the page will not reload and remove the values inserted in the form.
I want to validate my code with javaScript and determine if it is okay to submit to php.
If it is correct I want the form to not submit to the php file that I have in 'action'.
If it is inncorrect I do not want the form to submit to the php file, and I want to display an error message.
Right now the form uses "onsubmit="return Validate()"" to call the validation function which displays a message and returns false to stop the form action. The problem is that the form action does not get stopped, and still runs. For some reason when I click the submit button twice the php message gets displayed then the java script message gets displayed.
My html form:
<form action="<?= base_Url(); ?>index.php/Login/loginuser" onsubmit="return Validate();" method="post" name="Login" accept-charset= "utf-8" >
Username: <input type="text" name="Username" maxlength="21" />
<br><br>
Password: <input type="text" name ="password" maxlength="20" />
<br><br>
<input type = "submit" value = "Login" class = "loginbutton" />
</form>
My java script function.
function Validate() {
document.getElementById("errorMSG").innerHTML = "Validate ran...";
return false;
}
From what I read online when onsubmit="return Validate()" gets returned false the form is supposed to not run. Thought this was right but cant figure out why its not working.
EDIT: I am useing codeigniter to display the url, and for other purposes on the project.
EDIT2: This is still not working... When the onsubmit is changed too, onsubmit="false" the php will not be called. Which is expected. When changed to onsubmit="true", the php will be called. Which is expected.
When onsubmit="return Validate();" and the Validation() function on says "return false;". It will for as expected. Same with return true. But when code gets placed in the function the boolean does not appear to be returned. The code below will not stop the php file from running when the login name is empty.
function Validate() {
if (document.getElementsByName("Username")=="" )
{
document.getElementById("errorMSG").innerHTML = "Validate ran...";
return false;
}
else
{
return true;
}
}
I am testing with chrome and firefox. There are no error messages displayed in the console on google chrome. I am not familiar with the debug tool for fire fox but i see no error messages displayed either.
I am now going to change the jquery script line to an updated version, maybe it will help..
I am using code igniter with controllers, views, libraries...
Everything was working fine until i started with the javascript validation.
You should use return false only when mandatory fields are empty
function Validate() {
// check whether mandatory fileds have some value or not
// document.getElementsByName("Username") always returns an array and will be robust way to access value by index 0 iin array like - document.getElementsByName("Username")[0]
if(document.getElementsByName("Username")[0].value == "" || document.getElementsByName("password")[0].value)
{
document.getElementById("errorMSG").innerHTML = "All fields required";
return false;
}
return true;
}
Please try this one 100% work
onsubmit="myFunction();return false;"
1.It should be just "Validate()" for onsubmit, not "return Validate().
And use onclick instead of onsubmit
Try this
<input type = "submit" value = "Login" class = "loginbutton" onclick = "Validate()"/>
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!
I'm using a basic javascript email validation function and am trying to use jQuery to submit the form if conditions are met. However, the submit() function doesn't seem to be running for the email validation is met.
HTML
<form id="profile" action="" method="post">
<input type="text" id="email">\
<span class="error" id="email_err">Email address not valid.</span>
//Other Form data
</form>
<div id="form-submit">Submit</div>
jQuery/Javascript
function IsEmail(email) {
var regex = /^([a-zA-Z0-9_.+-])+\#(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/;
return regex.test(email);
}
jQuery(document).ready(function($){
$('#form-submit').click(function(){
var email = $('#email').val();
if(!IsEmail(email)){
$('#email_err').show();
$('#email').focus();
}else{
$('#profile').submit();
}
});
}
Now all I want it to do is catch the email validation. Actual form submittal and data writing I would like to handle as I have it set up now where the PHP for writing the data is on the current page (action=""). Originally, it was an actual form submit button but I wanted to try and validate the email without page refresh.
I figure my understanding of the submit() function might be off-point, as what I'm reading seems like it's just a listener for a form submit, but doesn't actually submit the form itself. Is this correct or do I just have a flub up somewhere?
Since you're just validating your form, you can simply return true or false if the form is valid or not.
Some variant of:
$("#profile").submit(function() {
var email = $('#email').val();
if (!IsEmail(email)) {
...
return false; // Form will not submit
}
...
return true; // Form will submit as usual
});
Make sure you use <input type="submit" /> since you're attaching directly to the submit event.
I am developing a web application in which I have created a form and in the onSubmit event of the form I have called a java script function which will check for "Field must not left blank" condition if it is left blank the form must not be posted so I have written following code:
Jsp Page Form
<form action="Result.jsp" name="validityCheck" onsubmit="return fnCheckEmptyField();">
<input type="text" name="txtIIDN" id="txtIIDN" style="font-size:medium;" onkeypress="return fnKeyPress(event)"/>
<input type="submit" id="btnValidityCheck" value="Check Validity" />
</form>
Javascript code is as follows
<script>
function fnCheckEmptyField()
{
var strDomain= document.getElementsByName("txtIIDN").value;
if(strDomain == null)
{
document.getElementById("lblValidityStatus").innerHTML="";
document.getElementById("lblValidityStatus").innerHTML="Domain Name Field Can't be Left Blank";
return false;
}
else
{
return true;
}
}
</script>
When I try to submit the form the javascript function gets executed and then form will gets posted whether the return value is true or false.
I dont want to submit the form when the return value is false i.e when field is empty
and also the condition in onsubmit event onsubmit="return fnCheckEmptyField(); showing me an error
Cannot return from outside a function or method.
Can you figure out what is the mistake I am commiting and possible solution for that?
Remove the onsubmit event on the form and In the submit button HTML, put this
<input type="submit" id="btnValidityCheck" value="Check Validity" onclick="return fnCheckEmptyField();" />
Adding on to what Furqan said, you should probably use the button and an onclick event to check the form, and if the form is valid, then call .submit() on your form.
I tend to not even use a submit button, I just have a normal button, and have it run javascript... then the javascript submits the form.
Example (HTML submit button):
<button id="btnValidityCheck" value="Check Validity" onclick="return fnCheckEmptyField();">Click Here</button>
Javascript function:
function fnCheckEmptyField() {
var strDomain= document.getElementsByName("txtIIDN").value;
if(strDomain == "") {
document.getElementById("lblValidityStatus").innerHTML="Domain Name Field Can't be Left Blank";
}
else {
document.getElementById("myFormId").submit();
}
}
Notice that if the javascript feel that the form is valid, THEN it will submit your form. You need to define an id for your form tag for this to work.
Also, I changed the == null check to == ""... that may have been causing issues...
Cheers!