I want to show an error if user enters less than 4 letters in text box.
Here is the code I'm currently using now, it is somewhat working. The problem is - it is showing the error and then it is submitting the value also.
I want to stop it submitting if user enters less than 4 letters.
JavaScript
<script type="text/javascript">
function check(what)
{
var length=what.search_text.value.length;
if (length >3 && length < 21)
what.submit();
else
alert("Your nick should be 4-20 characters long.");
}
</script>
HTML
<form method=post action=''><input type=hidden name=todo value=search>
<p align=center>
Enter Your Name:
<input type=text name=search_text value='$search_text'>
<input onclick=check(this.form); return false; type=submit value=Search>
</p>
</form>
<script type="text/javascript">
function check(what)
{
var length=what.search_text.value.length;
if (length >3 && length < 21){
what.submit();
}
else {
alert("Your nick should be 4-20 characters long.");
return false;
}
}
</script>
<?php
echo "<form method='post' action='' onsubmit='return check(this);'><input type=hidden name=todo value=search>
<p align=center>Enter Your Name: <input type=text name=search_text value='$search_text'><input type=submit value=Search></p><br>
</form>";
?>
Changes :
onsubmit='return check(this);' added in form tag
Removed onclick from button submit
return false; added in else condition of js function
Suggestion : Always try to use jQuery, It is simple and will reduce your code length.
in case of invalid values you need to
return false;
so that form submission is cancelled
u can achive this by using RegularExpressionValidator control
design your textbox like this example i am using.
<asp:TextBox ID="txtCityCode" runat="server" Width="147px" CssClass="txt" MaxLength="2"></asp:TextBox>
<asp:RequiredFieldValidator ID="rfvCityCode" runat="server" ErrorMessage="City Code is required information."
ControlToValidate="txtCityCode" Display="None" ValidationGroup="Save" SetFocusOnError="True"></asp:RequiredFieldValidator>
<asp:RegularExpressionValidator ID="revCityCode" runat="server" ErrorMessage="Numbers and special characters not allowed in 'City Code' field."
ControlToValidate="txtCityCode" ValidationExpression="^[a-zA-Z\s]+$" ValidationGroup="Save"
Display="None" SetFocusOnError="True"></asp:RegularExpressionValidator>
Just Change the ValidationExpression according to your needs
<script type="text/javascript">
function check(what)
{
var length=what.search_text.value.length;
if (length >3 && length < 21)
{ what.submit(); return true; }
else
{alert("Your nick should be 4-20 characters long.");
return false;}
}
</script>
and in HTML
<input onclick='return check(this.form)' type="submit" value="Search">
Related
I have an HTML form and using Javascript to validate the form. However, when I use setCustomValidity(), it doesn't seem to work properly. I have to click on the submit button twice to mark the field as invalid, and then when the correct input is entered, the field is not marked as valid again, i.e. the error message keeps repeating.
Here's my HTML:
<form id="data_form" onsubmit="event.preventDefault(); return validateForm();">
<table>
<tr>
<td colspan="2" class="right_align">
<label for="supplier_ref"> Supplier Reference Number: </label>
</td>
<td colspan="2">
<input id="supplier_ref" name="supplier_ref" type="number" required>
</td>
</tr>
<!-- more rows -->
<button id="generate" name="generate" type="submit" onclick=""> Generate Barcode </button>
</table>
</form>
Javascript:
function validateForm() {
var form = document.forms["data_form"];
var emptymsg = "Field must be filled out.";
var supplier_ref = form.elements["supplier_ref"];
var supplier_ref_value = supplier_ref.value.toString();
if (supplier_ref_value == "") {
supplier_ref.setCustomValidity(emptymsg);
return false;
}
if (supplier_ref_value.length != 9){
supplier_ref.setCustomValidity("Number has to be 9 digits long.");
return false;
} else {
supplier_ref.setCustomValidity("");
}
return true;
}
When the length of the Supplier Reference is less than 9 digits, the error message appears, but when I enter the correct length, I still get the same error.
I would appreciate any help.
Thanks in advance
Nvm it only works with addEventListener
Basically, I have this very simple HTML form, when I submit, it does POST to /productos and runs a JS script that validates the form, if its not correct, it displays an error, all good.
But one thing I want to do is to "cancel" the POST if the form doesn't pass that validation, is there any way to do it?
I have thought about making the POST from the javascript function instead of from the form itself, but I have no idea how to do that
html:
<form name="registro" action="/productos" method='post' onsubmit="return validacion()">
<div>titulo</div>
<input type="text", name="titulo"/>
<input type="submit">
</form>
js validation:
function validacion(){
var titulo=document.registro.titulo.value;
if (titulo == ""){
alert("error, titulo cant be empty")
} else if (titulo.length > 100){
alert("error, titulo cant be more than 100 characters long")
}
make validacion() return true or false
function validacion(){
var titulo=document.registro.titulo.value;
if (titulo == ""){
alert("error, titulo cant be empty")
return false;
} else if (titulo.length > 100){
alert("error, titulo cant be more than 100 characters long")
return false;
}
return true;
}
<!DOCTYPE html>
<html>
<body>
<form name="registro" action="/productos" method="post">
<div>titulo</div>
<input type="text", name="titulo" required="required" />
<input type="submit">
</form>
</body>
</html>
no need for javascript run abounts are needed.
Its easier to use standard html5 with xhtml compatibility method, like this, for form validation:
<!DOCTYPE html>
<html>
<body>
<form name="registro" action="/productos" method="post">
<div>titulo</div>
<input type="text", name="titulo" required="required" />
<input type="submit">
</form>
</body>
</html>
I've tried, I've researched, and I still can't figure out how to validate this form using jQuery. I've even tried to check out the jQuery API and I had no luck with it. This shouldn't be as hard as it seems. There are a few id's that i'm not using yet because I want to get what I have so far working before I continue. The best I could find for validating emails is just straight up JavaScript. Here's my code.
$(document).ready(function(){
$("#sendForm").click(function(){
var validForm=true; //set valid flag to true, assume form is valid
//validate customer name field. Field is required
if($("#custName").val()) {
$("#custNameError").html(""); //field value is good, remove any error messages
} else {
$("#custNameError").html("Please enter your name.");
validForm = false;
}
//validate customer phone number. Field is required, must be numeric, must be 10 characters
var inPhone = $("#custPhone").val(); //get the input value of the Phone field
$("#custPhoneError").html(""); //set error message back to empty, assume field is valid
if(!inPhone) {
$("#custPhoneError").html("Please enter your phone number.");
validForm = false;
} else {
//if( !$.isNumeric(inPhone) || Math.round(inPhone) != inPhone ) //if the value is NOT numerice OR not an integer. Rounding technique
if( !$.isNumeric(inPhone) || (inPhone % 1 != 0) ) //if the value is NOT numerice OR not an integer. Modulus technique
{
$("#custPhoneError").html("Phone number must be a number.");
validForm = false;
} else {
if(inPhone.length != 10) {
$("#custPhoneError").html("Phone number must have 10 numbers");
validForm = false;
}
}
}
//ALL VALIDATIONS ARE COMPLETE. If all of the fields are valid we can submit the form. Otherwise display the errors
if(validForm) {
//all values are valid, form is good, submit the form
alert("Valid form will be submitted");
//$("#applicationForm").submit(); //SUBMIT the form to the server
} else {
//form has at least one invalid field
//display form and associated error messages
alert("Invalid form. Display form and error messages");
}
}); //end sendform.click
}); //end .ready
function isEmail(email) {
var regex = /^([a-zA-Z0-9_.+-])+\#(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/;
return regex.test(email);
}
label {
width:150px;
display:inline-block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<h2></h2>
<h3>Form Validation Project - Complaint Form</h3>
<form id="form1" name="form1" method="post" action="">
<p>Please enter the following information in order to process your concerns.</p>
<p>
<label for="custName">Name:</label>
<input type="text" name="custName" id="custName" />
<span id="custNameError" class="errorMsg"></span>
</p>
<p>
<label for="custPhone">Phone Number: </label>
<input type="text" name="custPhone" id="custPhone" />
<span id="custPhoneError" class="errorMsg"></span>
</p>
<p>
<label for = "email">Email:</label>
<input type = "text" name = "emailAdd" id = "emailAdd" />
<span id = "emailError" class = "emailError"></span>
</p>
<p>Please Select Product Group:</p>
<p>
<label>
<input type="radio" name="custProducts" value="books" id="custProducts_0" />
Books
</label>
<br />
<label>
<input type="radio" name="custProducts" value="movies" id="custProducts_1" />
Movies
</label>
<br />
<label>
<input type="radio" name="custProducts" value="electronics" id="custProducts_2" />
Consumer Electronics
</label>
<br />
<label>
<input type="radio" name="custProducts" value="computer" id="custProducts_3" />
Computer
</label>
<br />
</p>
<p>Description of problem: (Limit 200 characters)</p>
<p>
<label for="custComplaint"></label>
<textarea name="custComplaint" id="custComplaint" cols="45" rows="5"></textarea>
</p>
<p>
<input type="submit" name="button" id="button" value="File Complaint" />
<input type="reset" name="button2" id="button2" value="Reset" />
</p>
</form>
<p> </p>
$("#button").click(function(e){
e.preventDefault(); // you need to stop the initial event to have a chance to validate
var validForm=true;
// etc...
You can use jquery.validate.js to validate your forms , it will overcome all your manual efforts to create the validation rules also it is providing the various predefined rules like required,email, minlength and maxlength, etc. So, it will be easier for you to achieve what you need very easily.
https://jqueryvalidation.org/
I have a simple jquery form validation and submission package - see if that's of any help - it's easy to install and you can customise quite a few things: https://github.com/sebastiansulinski/ssd-form
Just to get you started, your submit control in the html has id "button", so you should use $('#button').click, not $('#sendForm').click.
Also, if you want to stay on the page (like to do validations, show errors, etc), you have to prevent the form from submitting automatically when the button is clicked. There are lots of ways to do this, but the easiest way is to just change your button type from submit to button. Ie, replace this:
<input type="submit" name="button" id="button" value="File Complaint" />
with this:
<input type="button" name="button" id="button" value="File Complaint" />
------
That should get you started, at least your code will run, you can use console.log to debug, etc. Good luck.
UPDATE
I should add that if you take my advice, the form will never submit on it's own - that is good if some validation fails and you want to stay on the page and give some error feedback to the user.
When you do want the form to submit, you have to make it happen yourself. Again, there are lots of ways to do this, but the simplest one is probably:
$('#form1').submit();
I have a form that has a textarea field for input. I want an alert to pop up if the field is empty on submit.
I copied some code that works fine on an input field; however, it does not work for the textarea (it submits with no alerts whether empty or not).
I read through some other questions posted here and made some modifications.
Now, it alerts when empty, but it also alerts when there is text and does not submit.
I am new to this. I am using asp classic.
Code:
<form method="post" action="reasonProcess.asp" name="formName" onSubmit="return Validate()">
<table >
<tr>
<td>Please enter a reason for the change:<br>
<textarea style="width:675px;height:75px" rows="12" cols="10" name="changereason" > <%=dbchangereason%> </textarea></td>
</tr>
</table><br>
<input type=button value="Approve" onClick="javascript:saveAndSubmit()" class="btn" style="float:none;font-size:.78em;">
</form>
<script>
function saveAndSubmit()
{
// Check for reason entered.
if (!document.formName.changereason.value == '')
{
alert("Enter a reason.");
return false;
}
var queryString = "reasonProcess.asp?Approve=Yes";
document.formName.action=queryString;
document.formName.submit();
// window.close();
}
</script>
This is line of code that works properly with the input text field:
if (!document.formName.changereason.value)
I have also tried:
if (!document.formName.changereason.value.length == 0)
and get the alert without text and with text.
Thanks for any help.
UPDATED
'!' is the logical not operator in JavaScript.
The condition in your code say if the value of changereason textarea is not empty show alert() because of the ! sign that mean not, but what you want is the contrary (if field is empty then show alert), so try just to remove the sign and it will work, do the follow change :
Replace :
if (!document.formName.changereason.value == '')
{
alert("Enter a reason.");
return false;
}
By :
if (document.formName.changereason.value == '') //removing the ! sign in this line
{
alert("Enter a reason.");
return false;
}
See Working fiddle.
If that not work take a look at External simple page with the same code that is not a fiddle and it should work also in your machine, code of external example :
<!DOCTYPE html>
<html>
<head><title></title>head>
<body>
<form method="post" action="reasonProcess.asp" name="formName" onSubmit="return Validate()">
<table >
<tr>
<td>Please enter a reason for the change:<br>
<textarea style="width:675px;height:75px" rows="12" cols="10" name="changereason" > <%=dbchangereason%> </textarea>
</td>
</tr>
</table>
<br>
<input type=button value="Approve" onClick="javascript:saveAndSubmit()" class="btn" style="float:none;font-size:.78em;">
</form>
<script>
function saveAndSubmit()
{
// Check for reason entered.
if (document.formName.changereason.value == '')
{
alert("Enter a reason.");
return false;
}
var queryString = "reasonProcess.asp?Approve=Yes";
document.formName.action=queryString;
document.formName.submit();
// window.close();
}
</script>
</body>
</html>
If that work and not the first example then maybe you have another part of code tha caused a problem and that is not referenced in the question.
Good luck.
change
if (!document.formName.changereason.value == '')
{
alert("Enter a reason.");
return false;
}
to
if (document.formName.changereason.value == '')
{
alert("Enter a reason.");
return false;
}
The ! means "not" - so you were saying if the value is not empty then alert.
In form tag write
<form action="" method="post" enctype="multipart/form-data" onsubmit="return checkform(this);">
This is your input field
<textarea name="reviewValue"></textarea>
Javascript Code:
<script language="JavaScript" type="text/javascript">
function checkform ( form ){
if (form.reviewValue.value == "") {
alert( "Please choice your Rating." );
form.reviewValue.focus();
return false ;
}
return true ;
}
</script>
I can't understand why my javascript isn't working... Do i need to declare a variable somewhere?
<script type="text/javascript">
function validation(form) {
if(form.first_name.value == '' ) {
alert('Please enter your first name');
form.first_name.focus();
return false;
}
if(form.00N30000006S4uq.value == '') {
alert('Please enter the high end of your budget');
form.company.focus();
return false;
}
return true;
}
</script>
<form action="https://www.salesforce.com/servlet/servlet.WebToLead" method="POST" onsubmit="return validation(this);">
As mentioned by #ReturnTrue, the NAME must begin with a letter. That is why your script is failing.
In your case since the field is auto-generated, if you know the flow of the elements in the form then you can reference the form elements array, like this...
form.elements[2].value
where form.elements[2] is form.00N30000006S4uq. That will do the job.
Example:
function validation(form) {
if(form.elements[0].value == '' ) {
alert('Please enter your first name');
form.first_name.focus();
return false;
}
if(form.elements[2].value == '') {
alert('Please enter the high end of your budget');
form.company.focus();
return false;
}
return true;
}
<form action="" method="POST" onSubmit="return validation(this);">
<input type="text" name="first_name" />
<input type="text" name="company" />
<input type="text" name="00N30000006S4uq" />
<input type="submit" name="submit" />
</form>
Form names need to begin with a letter. "00N30000006S4uq" fails because it begins with a number.
See: http://www.w3.org/TR/html401/types.html#type-cdata