I am trying to validate some text-fields using the required keyword, yet nothing is working?
How do I create validation using the required keyword.
Here is my code:
<div id="Name" class="tabcontent">
<form>
<div class="nameDiv">
Title: <input type="text" name="Title" title="Title" id="TitleTransfer">
</div>
<br>
<div class="addressDiv">
Name: <input type="text" name="name" id="NameTransfer" required />
<span class="asterisk"></span>
</div>
<br>
<div class="emailDiv">
Surname:
<input type="text" name="surname" id="LastNameTransfer" required />
<span class="asterisk"></span>
</div>
<br>
<div class="numberDiv">
Email Address:
<input type="text" name="email Address" id="EmailTransfer" required />
<span class="asterisk"></span>
</div>
<br>
<div class="numberDiv">
Phone number:
<input type="text" name="Phone number" id="NumberTransfer">
</div>
<button id="save-btnOne" onclick="moveContentOne()">Save</button>
</form>
</div>
the required attributes tells the browser that the form field must contain something, this is a weak validation and can be supressed when hooking the form submit through javascript (keep in mind that you do not have delivered any kind of javascript source here that might be in the orbit of the form).
I assume that the moveContentOne() hooking the onclick-event is the only javascript attached. Considering this the onSubmit-event remains untouched and will be also fired alongside of your onClick intervention. You should prefer to hook onSubmit for forms of that kind to apply custom validation, but that might detach the browser's default behavior for form validation (including the required-attachment to fields).
You might take a look at this guide: Form data validation
function validateForm() {
var x = document.forms["myForm"]["fname"].value;
if (x == "") {
alert("Name must be filled out");
return false;
}
}
Use this type of validation.
This works for
<form name="myForm" onsubmit="validateForm()">
<input type="text" name="fname" />
</form>
Some browsers do not support required field.
Change the code to your need.
I hope it helps you.
Related
I am not web developer, but I have a task to add autocomplete function for an input box. Please treat me as a very beginner.
<div>
<label id="email_label" for="send_email" style="padding-right:5px">
Send Email:
</label>
<input id="send_email" type="text" placeholder="e.g. xx.yy#zz.com" />
<button id="ack" onclick="requestAck()">
Request
</button>
</div>
requestAck() is a javascript function sending a email to address given by user (i.e. address in <input >). I am trying to add a flag in <input autocomplete="on" ...>, but it doesn't work. Perhaps because it's not in a <form></form> environment.
Could you help me to modify this code adding autocomplete (from cache) without changing other functions. Many thanks!
Try setting the property name="email" on the input tag, without that set the browser doesn't know what's supposed to autocomplete the field with :)
protip: I warmly suggest you to set the type of the input to email with type="email" instead of text, it's not required but it will help validating the input!
check this code:
<div>
<label id="email_label" for="send_email" style="paddingright:5px">Send Email:</label>
<input id="send_email" type="email" name="email" placeholder="e.g. xx.yy#zz.com" />
<button id="ack" onclick="requestAck()">Request</button>
</div>
EDIT: Final solution discussed in comments
<form onsubmit="submitForm(event)">
<label id="email_label" for="send_email" style="padding-right:5px">Send Email:</label>
<input id="send_email" type="email" autocomplete="email" name="email" placeholder="e.g. xx.yy#zz.com" />
<button id="ack" type="submit">Request</button>
</form>
<script>
function submitForm(e) {
e.preventDefault(); // this prevents the page from reloading
requestAck();
}
//dummy function so the javascript won't crash:
function requestAck() {}
</script>
Working example: https://codesandbox.io/s/focused-cray-ubkw4
I’m trying to create a form that ensures the name input field excludes the ‘#‘ symbol but also has the same box appear prompting the user to fill in the field if empty. I assume the box may differ per browser.
To explain my demo further, see this default form:
<form id='form-id' action="/" method="post">
<div class="subscribe-form">
<div class="form-section">
<div>
<input type="text" name="first_name" placeholder="name here" id="name-id" required />
</div>
<div>
<input type="text" name="email" placeholder="Email*" id="email-id" required />
</div>
<input id='checkbox-id' type="checkbox" required /> *check here
</div>
<button type="submit" value="Subscribe">submit</button> <!-- WITH input type submit -->
</div>
</form>
Clicking the submit button will only submit if all fields are completed, but it won’t check if the name field includes an ‘#‘. I can’t edit it to only submit if the field doesn’t include an ‘#‘.
But this demo:
<form id='form-id' action="/" method="post">
<div class="subscribe-form">
<div class="form-section">
<div>
<input type="text" name="first_name" placeholder="name here" id="name-id" required />
</div>
<div>
<input type="text" name="email" placeholder="Email*" id="email-id" required />
</div>
<input id='checkbox-id' type="checkbox" required /> *check here
</div>
<button onclick="checkName()" type="button" value="Subscribe">submit</button> <!-- changed from input type submit -->
</div>
<script>
let form = document.getElementById('form-id'),
ecsName = document.getElementById('name-id'),
ecsEmail = document.getElementById('email-id'),
ecsCheckbox = document.getElementById('checkbox-id');
function checkName() {
let name = ecsName.value,
email = ecsEmail.value;
if(name.includes('#')) {
alert('includes #');
} else if (name == '' || email == '') {
alert('please fill in your details');
} else if (ecsCheckbox.checked == false) {
alert ('unckeded');
} else {
form.submit();
}
}
</script>
</form>
Includes javascript that ensures all fields are completed, but I don’t like the alert and want the same prompt box to appear as with the former form.
Is there any way of doing this? I’m essentially trying to not tamper with the form and let the default settings do most of the work if possible. Also, another quick question - should required be required='required'? Thanks for any help here.
I have an ASP.NET MVC web page which is essentially a form to fill in and select certain fields. I am using twitter bootstrap as well.
My.cshtml
#{
ViewBag.Title = "MyWork";
}
#section Scripts {
#Scripts.Render("~/scripts/mywork.js")
#Scripts.Render("~/scripts/typeahead.min.js")
}
<br />
<legend>Add items to enable work</legend>
<div class="row">
<div class="col-md-2">
Item name:
</div>
<div class="col-md-8">
<input id="ItemTextBox" name="Name" type="text" placeholder="Enter an item name ..." class="form-control" required="required" autofocus="autofocus" />
</div>
</div>
<legend>Generate file</legend>
<input id="GenerateFile" type="submit" class="btn btn-primary" value="Generate File" onclick="javascript:generateFile()" />
The javascript file mywork.js contains the generateFile() method and creates a file using the items entered.
How should I validate that the ItemTextBox is not empty? There can be a number of items added so I obviously don't want to check for each text element. I have set the required="required" for the inputs. How can I auto-validate the required fields?
Without any plug-in, for browser's default validation,
wrap your input elements with <form></form>. And add "required" attribute to all required input fields.
<form id="myform">
<p><span>Item 1</span> <input name="Item 1" type="text" placeholder="Enter an item name"required="required" autofocus="autofocus" /></p>
<p><span>Item 2</span> <input name="Item 2" type="text" placeholder="Enter an item name"required="required" autofocus="autofocus" /></p>
<p><span>Item 3</span> <input name="Item 3" type="text" placeholder="Enter an item name"required="required" autofocus="autofocus" /></p>
<p><input type="submit" value="Generate File"/></p>
</form>
Call generateFile function when form get submitted (your form won't get submitted until all required fields are filled) and prevent browser from submitting form to server.
document.getElementById('myform').onsubmit = function(e) {
generateFile();
e.preventDefault();
}
function generateFile(){
alert('Generating File');
}
DEMO
I think this link might help you:
Jquery Validation plugin
As you have added a "required" attribute, you can just validate a form and then call your javascript method using the above plugin:
$("#myform").validate({
submitHandler: function(form) {
// some other code
// maybe disabling submit button
// then:
$(form).submit();
}
});
did you tried jQuery validation engine, its a nice and best plugin to validate your form controls very easily. Just have a look at below link (its a demo)
http://www.position-relative.net/creation/formValidator/demos/demoValidators.html
To download and for documentation visit
https://github.com/posabsolute/jQuery-Validation-Engine
I have a form which consists of 2 steps. What I'd like to do is validate each step before continuing to the next; the user should not be able to get to step 2 of step 1's fields are invalid.
js fiddle: http://jsfiddle.net/Egyhc/
Below you can find the simplified version of the form:
<form>
<div id="step1" style="display: block;">
<label for="first_name">First Name</label>
<input type="text" value="" name="first_name" id="FirstName"/>
<label for="last_name">Last Name</label>
<input type="text" value="" name="last_name" id="LastName"/>
</div>
<div id="step2" style="display: none;">
<label for="first_name">Address</label>
<input type="text" value="" name="address" id="Address"/>
</div>
Continue to step 2
<input type="submit" id="submit_btn" value="Verstuur" style="display: none;" />
</form>
$(function() {
$('#step1_btn').click(function() {
$('#step1').hide();
$('#step2, #submit_btn').show();
});
});
How do you guys suggest I achieve this?
There's a very neat setting of jQuery validate that lets you ignore validation on hidden fields. So you can handle the show/hide logic of your steps and for validation you could just do this:
As this suggests: ignore hidden
$("form").validate({
ignore: ":hidden"
});
If you need to check for validation on something besides the default form submit, you can use the valid method like this: $("form").valid().
I noticed you don't have any validation classes on your form, so I'm assuming you're handling that somewhere else. Just in case you're not, you can tell jQuery validate your rules through css classes like this: <input type="text" class="required digits"/>
See more here: http://bassistance.de/2008/01/30/jquery-validation-plugin-overview/
I have a pretty straight-forward javascript form validation script written:
function validateForm(){
var x=document.forms["contactForm"]["firstname"].value;
if (x==null || x==""){
return false;
}
var y=document.forms["contactForm"]["lastname"].value;
if (y==null || y==""){
return false;
}
var z=document.forms["contactForm"]["emailaddress"].value;
var atpos=z.indexOf("#");
var dotpos=z.lastIndexOf(".");
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=z.length){
return false;
}
var msg_area = document.getElementById("message");
msg_area.innerHTML = "";
if (document.getElementById("message").value.length < 20) {
return false;
}
else document.getElementById("contactForm").submit();
}
It's supposed to be validating this form:
<form name="contactForm" onsubmit="return validateForm()" action="./thankyou.html" method="post">
<label for="firstName">First Name <sup>*</sup></label>
<input name ="firstname" id="firstName" type="text" placeholder="First Name" required />
<label for="lastName">Last Name <sup>*</sup></label>
<input name ="lastname" id="lastName" type="text" name="lastName" placeholder="Last Name" required />
<label for="emailaddress">Email address <sup>*</sup></label>
<input name="emailaddress" id="emailAddress" type="email" placeholder="something#example.com" required />
<label for="message">Message<sup>*</sup></label>
<textarea id="message" placeholder="Remember, be nice!" required></textarea>
<input type="submit" name="submit" value="Email Me!" class="emailsub" />
<p class="small"><sup>*</sup> denotes a required field.</p>
</form>
When it's submitted, it doesn't seem to actually call the javascript at all. The only thing that it looks for is that it meets the "required" part of the html. I'm pretty new to javascript so it's probably glaringly obvious where the problem is, but I just can't locate it myself.
Any help is much appreciated!
p.s. this is for a local website at the moment so the action="" goes to another html instead of a page to process the message. Is this possibly the problem here?
The html5 "required" attribute tells the browser to validate before proceeding, read more here. This means that it's stopping the event before the javascript function is even called (on supported browsers) unless it passes the basic validation (required fields and email).
If you want the javascript to execute and perform your own validation, you'll need to remove the "required" attribute. You may also try more complex html form validation. Here is a good article on the subject.