i'm using javascript to validate my html (checking if the user input a correct data ) source code and it's more than simple but the problem is that when i press the submit button i can't see any result or alert
<script type= "text/javascript">
function checkname()
{
name = document.getElementById("myname");
var reg= /^[A-Z][a-z]+$/
if (!name.value.match(reg))
{
alert("Please enter your name begin with a CAPITAL letter");
return false;
}
if ( name.value=="")
{
alert("you kindly forget to put your name here");
return false;
}
return name.value("Welcome" + name + " to valet parking service VPS");
}
</script>
that's all for the first part where the script is written now in the html tag where the button is typed
<input type="submit" value=" submit " >
and that's what written in the form
<form onsubmit = " checkname(); return false; ">
This is the mistake (you always return false to the submit function):
<form onsubmit = " checkname(); return false; ">
Try this:
<form onsubmit="return checkname();">
Then modify your checkname function to something like this:
function checkname()
{
var name = document.getElementById("myname");
var reg= /^[A-Z][a-z]+$/
if (!name.value.match(reg))
{
alert("Please enter your name begin with a CAPITAL letter");
return false;
}
if ( name.value=="")
{
alert("you kindly forget to put your name here");
return false;
}
name.value("Welcome" + name + " to valet parking service VPS");
return true;
}
Here is the JSFiddle: http://jsfiddle.net/267wL/
HTML
<form action="demo.html" id="myForm" onsubmit = "checkname(); return false; " method="post">
<p>
<label>First name:</label>
<input type="text" id="myname" />
</p>
<input type="submit" value=" submit "/>
</form>
JavaScript
function checkname()
{
var name = document.getElementById("myname");
var reg= /^[A-Z][a-z]+$/;
if (!name.value.match(reg))
{
alert("Please enter your name begin with a CAPITAL letter");
return false;
}
name.value = "Welcome " + name.value + " to valet parking service VPS";
return false;
}
You don't have to check null values. If the name.value is empty, your regex validation failed.
Pay also attention that the welcome message is set in the input text. Weird behaviour...
The return true; will block all following code.
Try This
<script> function checkname() {
var x = document.forms["myForm"]["myname"].value;
if (x==null || x=="") {
alert("First name must be filled out");
return false;
}
}
<form name='myForm' action='action.php' onsubmit='return checkname()' method='post'>
First name: <input type="text" name="myname"><input type="submit" value="Submit"></form>
Related
Hi I'm trying to make this code more clean. I struggle with arrays and loops and have no idea how to convert this into into a loop. This is javascript for a form on an html page and if they leave a field blank, when they hit submit it should return an alert box and if everything is submitted properly it should confirm with them. There's also a reg exp for an acceptable postal code entry.
function validate()
{
var register = document.forms[0];
if (register.fname.value === "")
{
alert("Please fill out your first name.");
return false;
}
else if(register.lname.value === "")
{
alert("Please fill out your last name.");
return false;
}
else if(register.address.value === "")
{
alert("Please fill out your address.");
return false;
}
else if(register.postal.value ==="")
{
alert("Please enter a valid postal code.");
return false;
}
else if(!checkPostal(register.postal.value))
{
alert("Please enter a valid postal code.");
return false;
}
else if(register.eAddress.value === "")
{
alert("Please fill out your email address.");
return false;
}
return confirm("Is the information correct?");
}
//postal code regExp
function checkPostal()
{
var myReg = /^[A-Z]\d[A-Z] ?\d[A-Z]\d$/ig;
return myReg.test(document.getElementById("postal").value);
}
You can make this a pure HTML solution if you want to reduce javascript:
inputs have a required attr ref
additionally, inputs have a pattern attr ref that supports regex.
This kind of solution lets the browser handle feedback
<form>
<label>first name:
<input type="text" name="fname" required
minlength="1">
</label><br/>
<label>last name:
<input type="text" name="lname" required
minlength="1">
</label><br/>
<label>postal code:
<input type="text" name="zip" required pattern="^[A-Z]\d[A-Z] ?\d[A-Z]\d$"
minlength="1">
</label><br/>
<input type="submit" />
</form>
$.each( $( "#input input" ), function( key, element ) {
if( !$(element).val() ) {
$( "#error" + key ).text( "Input " + $( element ).attr( "name" ) + " is required");
return false;
}
});
Set your message as attribute on each element of the form like this:
<form method="POST" action="submit.php">
<input id="item1" type="text" value="" data-message="My error message" data-must="true">
...//do the same for other elements...
</form>
Now loop like below
var elements = document.forms[0].elements;
for (var i = 0, element; element = elements[i++];) {
if (element.getAttribute("must") && element.value === ""){
alert(element.getAttribute("message"));
return false;
}
}
return confirm("Is the information correct?");
Im just started with javascript and this is for testing.
I have basic login form with username and password, and added some Javascript to pickup username and password values, check them and if its true should redirect me to another html page.
In this case Im used window.location..
Here is the code
function Validate() {
username = document.login.korisnicko.value;
password = document.login.lozinka.value;
if (username == "" || password == "") {
window.alert ("Ne valja");
return false;
}
else if (password.length < 6) {
window.alert("mora biti duze od 6 slova");
return false;
}
else {
window.location = "profil.html";
return true;
}
}
<form name = "login">
<h1 id="greska"></h1>
<p id="greska2"></p>
<label>Korisnicko</label> <br>
<input type ="text" id="korisnicko" name="korisnicko"> <br>
<label>Lozinka</label> <br>
<input type ="password" id="lozinka" name="lozinka"> <br>
<button type = "submit" onclick="Validate();">Submit</button>
</form>
Here's a working fiddle:
http://jsfiddle.net/uLbycrhm/1/
I wouldn't recommend using window.location instead of the proper location.href, and I wouldn't recommend using window.alert instead of alert either (what's the difference?), so I've adjusted that as well. Using return here is unnecessary as well, because your function's tied to an onclick, not an onsubmit.
It's important to know that location is kind of an object, here is a link for your reference: MDN.
you can call function with return keyword
<script>
function Validate() {
username = document.login.korisnicko.value;
password = document.login.lozinka.value;
if (username == "" || password == "") {
alert ("Ne valja");
return false;
}
else if (password.length < 6) {
alert("mora biti duze od 6 slova");
return false;
}
else {
window.location = "profil.html";
return false;
}
}
</script>
<form name = "login" method="REQUEST" action=>
<h1 id="greska"></h1>
<p id="greska2"></p>
<label>Korisnicko</label> <br>
<input type ="text" id="korisnicko" name="korisnicko"> <br>
<label>Lozinka</label> <br>
<input type ="password" id="lozinka" name="lozinka"> <br>
<button type = "submit" onclick="return Validate();">Submit</button>
</form>
I am working with a form and would like to print the user's input with the first letter of each word capitalized no matter how they type it in. For example, I want the user's "ronALd SmItH" to print as Rondald Smith. I would also like to do this for the address and city. I have read all of the similar questions and answers on here and they are not working for me. I am not sure if I am putting my code in the wrong place or what I'm doing wrong.
This is the code I am using:
function correctFormat(customer)
{
var first = customer.charAt(0).toUpperCase();
var rest = customer.substring(1).toLowerCase();
return first + rest;
}
I have tried placing that in a variety of places within the whole document, I have tried renaming the string (eg. name, city, address). I have also read the others postings on here with what seems like the same question as this but none are working. I am not entering a string that I want capitalized. The user is entering their data into a form and I need it to print in an alert in the correct format. Here is the above code within the entire document. I am sorry it is so long but I am again, at a loss.
<html>
<!--nff Add a title to the Web Page.-->
<head>
<title>Pizza Order Form</title>
<script>
/*nff Add the doClear function to clear the information entered by the user and enter the information to be cleared when the clear entries button is clicked at the bottom of the Web Page.*/
function doClear()
{
var elements = document.getElementsByTagName('select');
elements[0].value = 'PA';
document.PizzaForm.customer.value = "";
document.PizzaForm.address.value = "";
document.PizzaForm.city.value = "";
document.PizzaForm.state.value = "";
document.PizzaForm.zip.value = "";
document.PizzaForm.phone.value = "";
document.PizzaForm.email.value = "";
document.PizzaForm.sizes[0].checked = false;
document.PizzaForm.sizes[1].checked = false;
document.PizzaForm.sizes[2].checked = false;
document.PizzaForm.sizes[3].checked = false;
document.PizzaForm.toppings[0].checked = false;
document.PizzaForm.toppings[1].checked = false;
document.PizzaForm.toppings[2].checked = false;
document.PizzaForm.toppings[3].checked = false;
document.PizzaForm.toppings[4].checked = false;
document.PizzaForm.toppings[5].checked = false;
document.PizzaForm.toppings[6].checked = false;
document.PizzaForm.toppings[7].checked = false;
document.PizzaForm.toppings[8].checked = false;
return;
}
//nff Add a doSubmit button to indicate what the outcome will be when the user clicks the submit order button at the bottom of the form.
function doSubmit()
/*nff Add an if statement to the doSubmit function to return false if there is missing information in the text fields once the user clicks the submit order button.*/
{
if (validateText() == false) {
return false;
}
//nff Add an if statement to the doSubmit function to return false if there is no pizza size selected using the radio buttons.
if (validateRadio() == false) {
return false;
}
//nff Add an if statement to the doSubmit function to return false if there are no toppings selected using the checkboxes.
if (validateCheckbox() == false) {
return false;
}
//nff Add an if statement to the doSubmit function to return false if the email entered by the user is empty or does not fit the acceptable format.
if (validateEmail() == false) {
return false;
}
/*nff Add an if statement to the doSubmit function to return false if the phone number entered by the user is empty or does not fit the acceptable formats.*/
if (validatePhone() == false) {
return false;
}
if (validateZip() == false) {
return false;
}
//nff Add an alert box to show customer information from text fields when the Submit Order button is clicked.
var customer = document.PizzaForm.customer.value;
var address = document.PizzaForm.address.value;
var city = document.PizzaForm.city.value;
var state = document.PizzaForm.state.value;
var zip = document.PizzaForm.zip.value;
var phone = document.PizzaForm.phone.value;
var email = document.PizzaForm.email.value;
var size = "";
for (var i = 0; i < document.PizzaForm.sizes.length; i++) {
if (document.PizzaForm.sizes[i].checked) {
size = document.PizzaForm.sizes[i].nextSibling.nodeValue.trim();
break;
}
}
var toppings = [];
for (var i = 0; i < document.PizzaForm.toppings.length; i++) {
if (document.PizzaForm.toppings[i].checked) {
toppings.push(document.PizzaForm.toppings[i].nextSibling.nodeValue.trim());
}
}
alert("Name: " + customer + '\n' +
"Address: " + address + '\n' +
"City: " + city + '\n' +
"State: " + state + '\n' +
"Zip: " + zip + '\n' +
"Phone: " + phone + '\n' +
"Email: " + email + '\n' +
"Size: " + size + '\n' + (toppings.length ? 'Toppings: ' + toppings.join(', ') : ''));
}
//nff Add the validateText function to ensure that all text fields are complete before the order is submitted.
function validateText() {
var customer = document.PizzaForm.customer.value;
if (customer.length == 0) {
alert('Name data is missing');
document.PizzaForm.customer.focus();
return false
};
var address = document.PizzaForm.address.value;
if (address.length == 0) {
alert('Address data is missing');
return false;
}
var city = document.PizzaForm.city.value;
if (city.length == 0) {
alert('City data is missing');
return false;
}
var state = document.PizzaForm.state.value;
if (state.length == 0) {
alert('State data is missing');
return false;
}
var zip = document.PizzaForm.zip.value;
if (zip.length == 0) {
alert('Zip data is missing');
return false;
}
var phone = document.PizzaForm.phone.value;
if (phone.length == 0) {
alert('Phone data is missing');
return false;
}
var email = document.PizzaForm.email.value;
if (email.length == 0) {
alert('Email data is missing');
return false;
}
return true;
}
//nff Add the validateRadio function so that if none of the radio buttons for pizza size are selected it will alert the user.
function validateRadio() {
if (document.PizzaForm.sizes[0].checked) return true;
if (document.PizzaForm.sizes[1].checked) return true;
if (document.PizzaForm.sizes[2].checked) return true;
if (document.PizzaForm.sizes[3].checked) return true;
alert('Size of pizza not selected');
document.PizzaForm.sizes[0].foucs();
return false;
}
//nff Add the validateCheckbox function so that if none of the checkboxes for toppings are selected it will alert the user.
function validateCheckbox() {
if (document.PizzaForm.toppings[0].checked) return true;
if (document.PizzaForm.toppings[1].checked) return true;
if (document.PizzaForm.toppings[2].checked) return true;
if (document.PizzaForm.toppings[3].checked) return true;
if (document.PizzaForm.toppings[4].checked) return true;
if (document.PizzaForm.toppings[5].checked) return true;
if (document.PizzaForm.toppings[6].checked) return true;
if (document.PizzaForm.toppings[7].checked) return true;
if (document.PizzaForm.toppings[8].checked) return true;
alert ('Toppings are not selected');
return false;
}
//nff Add the validateEmail function to ensure that the email address has been entered in the correct format.
function validateEmail() {
if (/^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{3,4})+$/.test(PizzaForm.email.value))
{
return (true)
}
alert("You have entered an invalid email address")
return (false)
}
//nff Add the validatePhone function to ensure that the phone number has been entered in any of the acceptable formats.
function validatePhone() {
if (/^[(]{0,1}[0-9]{3}[)]{0,1}[-\s\.]{0,1}[0-9]{3}[-\s\.]{0,1}[0-9]{4}$/.test(PizzaForm.phone.value))
{
return (true)
}
alert("You have entered an invalid phone number")
return (false)
}
function validateZip() {
if (/^\d{5}([\-]\d{4})?$/.test(PizzaForm.zip.value))
{
return (true)
}
alert("You have entered an invalid zip")
return (false)
}
function correctFormat(customer)
{
var first = customer.charAt(0).toUpperCase();
var rest = name.substring(1).toLowerCase();
return first + rest;
}
</script>
</head>
<body>
<!--nff Add a form for the user to enter information into.-->
<form name="PizzaForm">
<!--nff add a title at the top of the Web Page-->
<h1>The JavaScript Pizza Parlor</h1>
<!--nff add directions to the user for the information to be entered-->
<p>
<h4>Step 1: Enter your name, address, and phone number:</h4>
<!--nff change the font-->
<font face="Courier New">
<!--nff insert a text field for user to enter their name, add spaces between the title of the text box and the box itself, specify the size of the input box, and the type of input into the box as text.-->
Name: <input name="customer" size="50"
type="text"><br>
<!--nff insert a text field for user to enter their address, specify the size of the input box, and the type of input into the box as text.-->
Address: <input name="address" size="50" type="text"><br>
<!--nff Insert a text field for user to enter their city, add spaces between the title of the text box and the box itself, specify the size of the input box, and the type of input into the box as text.-->
City: <input name="city" size="15" type="text">
<!--nff Insert text fields for the user to enter their state and zip, specify the sizes of the input boxes, and specify that the text to be entered into the boxes will be in all caps for the state box. These input boxes should be on the same line as the last one.-->
State:<select name="state">
<option selected value="PA">PA</option>
<option value="NJ">NJ</option>
<option value="NY">NY</option>
<option value="DE">DE</option>
</select>
Zip: <input name="zip" size="5" type="text"><br>
<!--nff Insert a text field for the user to enter their phone number, insert spaces after the title of the box, specify the size of the box, and the type of input as text.-->
Phone: <input name="phone" size="50" type="text"><br>
<!--nff Insert a text field for the user to enter their email address, insert spaces after the title of the box, specify the size of the box, and the type of input as text.-->
Email: <input name="email" size="50" type="text"><br>
</font>
</p>
<!--nff add second step to order a pizza-->
<p>
<h4>Step 2: Select the size of pizza you want:</h4>
<font face="Courier New">
<!--nff Add radio buttons to choose from four options for pizza sizes.-->
<input name="sizes" type="radio" value="small">Small
<input name="sizes" type="radio" value="medium">Medium
<input name="sizes" type="radio" value="large">Large
<input name="sizes" type="radio" value="jumbo">Jumbo<br>
</font>
</p>
<p>
<!--nff add third step to order a pizza-->
<h4>Step 3: Select the pizza toppings you want:</h4>
<font face="Courier New">
<!--nff Add check boxes for user to choose toppings.-->
<input name="toppings" type="checkbox" value="pepperoni">Pepperoni
<input name="toppings" type="checkbox" value="canadian bacon">Canadian Bacon
<input name="toppings" type="checkbox" value="sausage">Sausage<br>
<input name="toppings" type="checkbox" value="mushrooms">Mushrooms
<input name="toppings" type="checkbox" value="pineapple">Pineapple
<input name="toppings" type="checkbox" value="black olives">Black Olives<br>
<input name="toppings" type="checkbox" value="green peppers">Green Peppers
<input name="toppings" type="checkbox" value="extra cheese">Extra Cheese
<input name="toppings" type="checkbox" value="none">None<br>
</font>
</p>
<!--nff Add buttons for the options to submit order or clear entries. Add an onClick event to show one of the alerts entered earlier in this document when the submit button is clicked at the bottom of the Web Page. Add and onClick event to clear the entries in this form upon clicking the clear entries button.-->
<input type="button" value="Submit Order" onClick="doSubmit()">
<input type="button" value="Clear Entries" onClick="doClear()">
</form>
</body>
</html>
You can use regular expression, such as this:
function correctFormat(customer){
return customer.replace(/\b(.)(.*?)\b/g, function(){
return arguments[1].toUpperCase() + arguments[2].toLowerCase();
});
}
Your function only capitalizes the first letter of the string but not the first letter of each word. You can try splitting the string into separate words using string.split(' '):
function correctFormat(customer)
{
if (customer == null || customer.length == 0)
return customer;
var words = customer.split(/\s+/g);
for (var i = 0; i < words.length; ++i) {
var first = words[i].charAt(0).toUpperCase();
var rest = words[i].substring(1).toLowerCase();
words[i] = first + rest;
}
return words.join(' ');
}
I also noticed that you do not call correctFormat anywhere. You need to call the function in order for it to be executed. For example:
var customer = correctFormat(document.PizzaForm.customer.value);
As mentioned by #Wee You, you use customer for the first letter but use name for the rest letters. You have to call this function with user inputs and then update text in dom with the correct format.
function correctFormat(str)
{
var first = str.charAt(0).toUpperCase();
var rest = str.substring(1).toLowerCase();
return first + rest;
}
Here's a tiny example of the code you need:
Pass to the .replace() method every name part:
var PizzaForm = document.PizzaForm;
var customer = PizzaForm.customer;
function formatName() {
this.value = this.value.replace(/([^ \t]+)/g, function(_, str) {
var A = str.charAt(0).toUpperCase();
var bc = str.substring(1).toLowerCase();
return A + bc;
});
}
customer.addEventListener("input", formatName);
<form name="PizzaForm">
Name: <input name="customer" size="50" type="text">
</form>
the above will work also on Paste. Have fun
PS: instead of all that doClear(){ wall of code, why don't you reset your form by simply using: PizzaForm.reset();
Try this function
function correctFormat(customer)
{
var upperText = customer.toLowerCase();
var result = upperText.charAt(0).toUpperCase();
for(var i=1;i<upperText.length;i++)
if(upperText.charAt(i-1) == ' ')
result += upperText.charAt(i).toUpperCase();
else
result += upperText.charAt(i);
return result;
}
I have HTML page with javascript. In this, I have form which contains text for name and checkboxes. Below is the HTML form:
<form name="drugForm" action="form1.php" onsubmit="return validateForm()" method="post">
First name: <input type="text" name="dname">
<pre>
<input type="checkbox" name="drug" value="id1">ID1 <input type="checkbox" name="drug" value="id2">ID2</br>
<input type="checkbox" name="drug" value="id3">ID3 <input type="checkbox" name="drug" value="id4">ID4</br>
</pre>
<input type="submit" value="Submit">
</form>
Below is the javascript for same:
<script>
function validateForm(){
var x=document.forms["drugForm"]["dname"].value;
//var y=document.drugForm.drug[0].value;
var y = new Array();
if (x==null || x=="")
{
alert("First name must be filled out");
return false;
}
else if (Boolean(x))
{
alert("click any checkbox "+ y);
//alert("Working with boolean " + y);
return false;
}
}
</script>
Here, I want to check whether any checkbox is checked also along with name entry. But whenever I am trying to put for loop with y (array) in else if condition or anywhere in function, the code is not working and instead giving action directly.
My question, specifically, is how to check checkboxes, like did in if condition, is checked and how to get those values?
The code below validate when there's at least one checked box:
function validateForm(){
var x=document.forms["drugForm"]["dname"].value;
var y=document.drugForm.drug;
if (x==null || x=="") {
alert("First name must be filled out");
return false;
} else if (Boolean(x)) {
for (k=0;k<y.length;k++) {
if(y[k].checked) {
return true;
}
}
alert("Check one option at least");
return false;
}
}
There's another goog option in jquery as shown in another post.
Try this,
function validateForm(){
var x=document.forms["drugForm"]["dname"].value;
if (x==null || x=="")
{
alert("First name must be filled out");
return false;
}
else if (x)
{
if(!$('input:checkbox:checked').length)//check length of checked checkboxes
{
alert("click any checkbox ");
return false;
}
}
}
I'm trying to make a basic form validation but it's not working. I need to make it in such a way that after validation is passed, THEN ONLY it submits the form. I'm not sure how to do it though. My code is below.
[Important request]
** I'm actually pretty new to this so if possible I would like to get some concrete information/explanation concerning the DOM and how to manipulate it and style it (W3School is NOT helping) **
<form id="reg" method="POST" action="user.php" onsubmit="return validate()">
<label for="first">First Name: </label>
<input id="first" name="first" type="text" value="">
<label for="last">Last Name: </label>
<input id="last" name="last" type="text" value="">
<button type="submit">Register</button>
</form>
function validate(){
if(document.getElementById('first').value == ""){
alert('First Name Blank!');
return false;
}else{
return true;
}
if(document.getElementById('last').value == ""){
alert('Last Name Blank!');
return false;
}else{
return true;
}
}
Thanks
Try this:
function validate() {
var validForm = true;
var msg = '';
if (document.getElementById('first').value == "") {
msg += 'First Name Blank! ';
validForm = false;
}
if (document.getElementById('last').value == "") {
msg += 'Last Name Blank! ';
validForm = false;
}
if (!validForm) {
alert(msg);
}
return validForm;
}
Plunker example
Your validation function only validates the first name. Whether it's valid or not, the function returns before checking the last name.
function validate(){
if(document.getElementById('first').value == ""){
alert('First Name Blank!');
return false; // WILL RETURN EITHER HERE ...
}else{
return true; // ... OR HERE
}
The return statement will exit the function at the point it appears, and other code after that is simply not executed at all.
Instead of doing it that way, keep a flag that determines whether the fields are all OK:
function validate(){
var isValid = true; // Assume it is valid
if(document.getElementById('first').value = ""){
alert('First Name Blank!');
isValid = false;
}
if(document.getElementById('last').value == ""){
alert('Last Name Blank!');
isValid = false;
}
return isValid;
}
Here's the code to check for validation and stop it from submitting if it is incorrect data.
<form id="reg" method="POST" action="user.php">
<label for="first">First Name: </label>
<input id="first" name="first" type="text" value="">
<label for="last">Last Name: </label>
<input id="last" name="last" type="text" value="">
<button type="button" id="submit">Register</button>
</form>
document.getElementById('submit').onclick = function(){
if(validate()){
document.getElementById('reg').submit();
}
}
function validate(){
if(document.getElementById('first').value == ""){
alert('First Name Blank!');
return false;
}else if(document.getElementById('last').value == ""){
alert('Last Name Blank!');
return false;
}else{
return true;
}
}
All I have done here is made the submit button a regular button and handled submitting via JS, When an input of type submit is clicked the page will submit the form no matter what. To bypass this you can make it a regular button and make it manually submit the form if certain conditions are met.
Your javascript code can be:
document.getElementById('submit').onclick = function () {
if (validate()) {
document.getElementById('reg').submit();
}
}
function validate() {
if (document.getElementById('first').value == "") {
alert('First Name Blank!');
return false;
} else if (document.getElementById('last').value == "") {
alert('Last Name Blank!');
return false;
} else {
return true;
}
}