I am new to this forum and am quite a novice at Javascript:
I am trying to do a simple form validation.
On the head part of the html file I have a function
function form_onchange(){
var Fname = document.getElementById('Fname');
var RegExpTxt = /^([a-zA-Z ]){2,30}$/;
if (!RegExpTxt(Fname.value)) {
alert('Please provide a valid name');
Fname.focus();
Fname.select();
return false;
}
}
This is just a part of the function I have other validation rules on it.
On the html part I have:
<table align="center" border = "1" bordercolor="#8B008B" cellpadding="5">
<form action = "Pizza Fun.html" name = "formA" method = "post" onsubmit = "return checkBlank() ">
<tr>
<td><p>Name</p></td>
<td><span>First </span><input type = "text" name = "Fname" id = "Fname" onchange = "form_onchange()" value = "first" />
<span>Last </span><input type = "text" name = "Lname" id = "Lname" onchange = "form_onchange()" value = "lat " />
</td>
</tr>
The validation part was working yesterday but now for the life of me is not working now. Please can anyone help me why it is not working.
Use RegExpTxt.test(Fname.value) instead of RegExpTxt(Fname.value)
Javascript should end up being:
function form_onchange(){
var Fname = document.getElementById('Fname');
var RegExpTxt = /^([a-zA-Z ]){2,30}$/;
if (!RegExpTxt.test(Fname.value)) {
alert('Please provide a valid name');
Fname.focus();
Fname.select();
return false;
}
}
Related
I'm a beginner in web development and I have an HTML form where a person can add his address , address number, region and postal code . In this form the address and the region have to contain only char letters .
(ex. Lakewood : correct Lakewood13 : error) . If any of these two variables contains a number I have to enter my data again to continue . Else, I move to the next page . I'm a complete beginner in javascript which I need to use to check my variable types and I would appreciate your help with guiding me to solve this problem .
This is my code with my HTML form with the address number and the region which are the variables we need in this problem :
function checkdata(){
//the two elements we need to check
var a = document.getElementById("address");
var r = document.getElementById("region");
if(typeof(a.value) === 'string'&&(typeof b.value) ==='string'){
//continue to next page(but how can I check if numbers are in the strings ?)
}
else{
//go back to form and enter again(how can I enter the elements again ? )
}
}
<div class = "form-area" id = "forma">
<form action="/action.page.html" class = "sign-form" >
<div class = "form-container">
<h1> Enter purchase data below : </h1>
<label for="addrs"> Address Name</label>
<input type = "text" placeholder = "Enter address name " id = "address" name = "addr" required/>
<label for="regn" > Region </label>
<input type = "text" placeholder = "Enter region " id = "region" name = "reg" required/>
</div>
<button type="submit" class="continuebtn" onclick = "checkdata()">Continue</button>
</form>
</div>
Thank you in advance .
You can try using regex to check if string contains any number in it:
if(!(/\d/.test(a.value)) && !(/\d/.test(b.value))){
Please Note: You also have to return false to prevent the default event if the condition is false and prefix return the function call in onclick attribute.
Demo:
function checkdata(){
//the two elements we need to check
var a = document.getElementById("address");
var r = document.getElementById("region");
if(!(/\d/.test(a.value)) && !(/\d/.test(r.value))){
alert('form submit');
}
else{
alert('no submit');
return false;
}
}
<div class = "form-area" id = "forma">
<form action="/action.page.html" class = "sign-form" >
<div class = "form-container">
<h1> Enter purchase data below : </h1>
<label for="addrs" Address Name</label>
<input type = "text" placeholder = "Enter address name " id = "address" name = "addr" required/>
<label for="regn" > Region </label>
<input type = "text" placeholder = "Enter region " id = "region" name = "reg" required/>
</div>
<button type="submit" class="continuebtn" onclick = "return checkdata()">Continue</button>
</form>
</div>
You can write a function for validity, then you can check for dependencies based on that **
function checkData() {
let adress = document.getElementById('address');
let region = document.getElementById('region');
function isValid(e) {
let isTrue;
for (let char in e) {
typeof e[char] !== 'string' ? alert('Please only type strings') : (isTrue = true);
}
return isTrue;
}
isValid(adress.value) && isValid(region.value) ? console.log('next page') : console.log('error');
}
checkData();
**
So need to check if the strings are containing numbers or not
hope you find more insight here: Check whether an input string contains a number in javascript
working demo :
// check if string contains number
function hasNumber(myString) {
return /\d/.test(myString);
}
function checkdata(e) {
e.preventDefault()
//the two elements we need to check
var a = document.getElementById("address");
var r = document.getElementById("region");
var isAddressContainsNumber = hasNumber(a.value);
var isRegionContainsNumber = hasNumber(r.value);
console.log(isAddressContainsNumber, isRegionContainsNumber)
if (isAddressContainsNumber === false && isRegionContainsNumber === false) {
console.log('None of string contains number')
} else {
console.log('One or Both string contains number')
}
}
const form = document.querySelector('.sign-form');
form.addEventListener('submit', checkdata);
<div class="form-area" id="forma">
<form class="sign-form">
<div class="form-container">
<h1> Enter purchase data below : </h1>
<label for "addrs" Address Name</label>
<input type="text" placeholder="Enter address name " id="address" name="addr" required/>
</label>
<label for "regn" > Region </label>
<input type="text" placeholder="Enter region " id="region" name="reg" required/>
</label>
</div>
<button type="submit" class="continuebtn">Continue</button>
</form>
</div>
I would recommend going through the string and getting the ASCII value of each character. Numbers 0-9 are ASCII characters 48-57. Javascript uses UTF-16 and the appropriate method (charCodeAt) returns a 16-bit UTF-16 value, but UTF-16 characters 0-127 match ASCII. So:
var testString = "abcd123";
var isValid = true;
for (var i=0;i<testString.length;i++)
{
if (testString.charCodeAt(i) > 47 && testString.charCodeAt(i) < 58)
{
isValid = false;
}
}
if (!isValid)
{
//Code here to alert the user
alert("There's a number in there!");
}
You are using typeof in wrong way, try this way
typeOf(variable you want to check)
I have a form in an html page that ends up being cleared after i click the submit button. I wanted to know how I to make the data stay in the form after clicking submit in case the user needs to fix any errors. Any help would be appreciated!
Here is the html code:
<form id = "contactform" action = "">
<label> Name:
<input name = "firstname" type = "text" id = "firstname" maxlength = "50"/>
</label>
<label> Last Name:
<input name = "lastname" type = "text" id = "lastname" maxlength = "150" />
</label>
<label> Address:
<input name = "address" type = "text" id = "address" maxlength = "200"/>
</label>
<label> Postcode:
<input name = "postcode" type = "text" id = "postcode" maxlength = "50" />
</label>
<input type = "submit" value = "Submit" onclick = "validate()" />
<input type = "reset" value = "Clear" />
</p>
</form>
and here is the javascript code:
function validate() {
var firstname = document.getElementById('firstname');
var lastname = document.getElementById('lastname');
var address = document.getElementById('address');
var postcode = document.getElementById('postcode');
if(firstname.value == "") {
alert("Make sure the first name field is filled");
return false;
}
if(lastname.value == "") {
alert("Make sure the last name field is filled");
return false;
}
if(address.value == "") {
alert("Make sure the address field is filled");
return false;
}
if(postcode.value == "") {
alert("Make sure the post code field is filled");
return false;
}
First, add a submit handler to your form:
<form id="contactform" action = "" onsubmit="handleSubmit()">
...
</form>
Then in your handler validate the input. If its not valid you need to preventDefault() to stop the form from submitting. Note: You'll have to return true at the end of validate() if nothing is wrong. I don't see that in the question.
function handleSubmit(event) {
if(!validate()) {
event.preventDefault();
}
return;
}
Add return with onclick onclick="return validate()"
function validate() {
var firstname = document.getElementById('firstname');
var lastname = document.getElementById('lastname');
var address = document.getElementById('address');
var postcode = document.getElementById('postcode');
if (firstname.value == "") {
alert("Make sure the first name field is filled");
return false;
}
if (lastname.value == "") {
alert("Make sure the last name field is filled");
return false;
}
if (address.value == "") {
alert("Make sure the address field is filled");
return false;
}
if (postcode.value == "") {
alert("Make sure the post code field is filled");
return false;
}
}
<form id="contactform" action="">
<label> Name:
<input name = "firstname" type = "text" id = "firstname" maxlength = "50"/>
</label>
<label> Last Name:
<input name = "lastname" type = "text" id = "lastname" maxlength = "150" />
</label>
<label> Address:
<input name = "address" type = "text" id = "address" maxlength = "200"/>
</label>
<label> Postcode:
<input name = "postcode" type = "text" id = "postcode" maxlength = "50" />
</label>
<input type="submit" value="Submit" onclick="return validate()" />
<input type="reset" value="Clear" />
</form>
I have a big problem with my client side and my server side and I need help.
I have to gather data from two forms and submit data after validation when the saveentry button of the third form is pressed but I am getting confused. The values do not get displayed and server side validation does not work. I have two forms which have to undergo client side and server side validation. I use the onsubmit so that when the form is posted the values are checked this is the code:
function validation() {
person_name = $('#person_name').val();
if (test_name == '') {
$('#test_name').parent().append('<div class="error">Please fill this field</div>');
errors = true;
}
if (errors) {
return false;
} else {
var personname = ("<h1>" + person_name + "</h1>");
$('#display').append('<div class = "display">' + personname + '</div>');
}
}
function validation1(){
var product_name = $('#product_name').val();
if(product_name == ''){
$('#product_name').parent().append('<div class="error">Please fill this field</div>');
// the other fields are validated as well
errors = true;
}
if(errors){
return false;
}
else{
// the values are appended to display
}
}
The forms look like this
<form name = "person" action = "" onsubmit= "return validation" method=" post" >
<input type="text" name = "personname" id = "personname">
</form>
<form name = "products" action = "" method = "post" onsubmit= "return validation1">
<input type="text" name = "productname" id = "productname">
<input type="text" name = "company" id = "company">
<input type="text" name = "location" id = "location">
</form>
<form name = "display" id = "display" action = "saveentry.php" method = "post">
</form>
the PHP code that checks the values is as follows
if(empty($_POST['fieldname'])){
//An error is displayed.
}
Any help is highly welcome!
Try next:
onsubmit= "return validation()"
function validate() {
var fname = document.getElementById("fname").value;
document.getElementById("errorfname").innerHTML = "";
if (checkfname() == true) {
alert("Entry submitted.");
} else {
return false;
}
}
function checkfname() {
var fname = document.getElementById("fname").value;
if (fname.length == 0) {
document.getElementById("errorfname").innerHTML = "Invalid first name. Cannot be empty.";
return false;
} else if (!isNaN(fname)) {
document.getElementById("errorfname").innerHTML = "Invalid first name. Cannot contain numbers.";
return false;
} else {
return true;
}
}
function addRow() {
if (validate() == true) {
}
}
<form>
First Name:
<input type="text" id="fname" name="fname" />
<p id="errorfname" class="red"></p>
<input id="submit" type="submit" value="Submit Entry" onclick="return addRow()" />
<input id="clear" type="button" value="Reset" onclick="reset()" />
</form>
<form>
<fieldset>
<label for = "firstnameinput">
First Name: <input type = "text" id = "fname" name = "fname" placeholder = "John"/>
<p id = "errorfname" class = "red"></p>
</label>
</fieldset>
<fieldset>
<label id = "submitbutton">
<input id = "submit" type = "submit" value = "Submit Entry" onclick = "return addRow();upperCase();"/>
</label>
<label id = "resetbutton">
<input id = "clear" type = "button" value = "Reset" onclick = "reset()"/>
</label>
</fieldset>
</form>
This is my simplified HTML file. It basically has an input and a paragraph below it to display an error message later on. For now it is set as "" in javascript. The HTML also has a submit button and a reset button. The purpose of the reset button is to clear all previously entered fields or any error message that has appeared.
function validate(){
var fname = document.getElementById("fname").value;
document.getElementById("errorfname").innerHTML = "";
if(checkfname() == true){
alert("Entry submitted.");
}
else{
return false;
}
function checkfname(){
var fname = document.getElementById("fname").value;
if(fname.length == 0) {
document.getElementById("errorfname").innerHTML = "Invalid first name. Cannot be empty.";
return false;
}
else if(!isNaN(fname)){
document.getElementById("errorfname").innerHTML = "Invalid first name. Cannot contain numbers.";
return false;
}
else{
return true;
}
}
function addRow(){
if(validate() == true){
event.preventDefault();
var fname = document.getElementById("fname").value;
firstNameArray.push(fname)
var row = document.getElementById('table').insertRow(-1);
var colNum = row.insertCell(0);
var colName = row.insertCell(1);
i++;
colNum.innerHTML = i;
colName.innerHTML = fname + " " + lname;
else{
return false;
}
reset();
}
Lastly, my reset() function below.
function reset(){
document.getElementById("errorfname").innerHTML = "";
document.getElementById("fname").value = "";
}
The problem is, for example, in the input box for fname, I enter John. When I press the reset button on my HTML which calls the reset() function, John in the box disappears so I got that going for me which is nice. However, lets say I purposely left the box blank to receive an error message, a red sentence below the box appears saying "Invalid first name. Cannot be empty." When I press the reset button to call onto the reset() function, this red error message does not disappear however, any current value inside the box disappears. This makes by reset() function work 50% only. I clearly stated for both to disappear in my reset() function.
TL;DR
I have a reset button in my HTML which calls a reset() function in my javascript. I have a name input box in my HTML and what the reset() function is supposed to do is to remove any current name which is inside the box as well as remove any error message that appears below. My reset() function is able to clear away any name inside the box currently but is unable to clear away the error message.
I created a fiddle to test your problem. I noticed the same thing. I changed the method reset() to resetTest() and it worked fine.
working fiddle
The reason changing the name worked is that onxyz= attribute event handlers are run (effectively) within a couple of with statements, one of which is with (theEnclosingFormElement). Form elements have a built-in reset method that clears all of their inputs to their initial values. So in this:
<input id = "clear" type = "button" value = "Reset" onclick = "reset()"/>
The reset being called isn't your reset, it's the form's reset, which doesn't (of course) do anything with errorfname. Changing the name removes the conflict.
see the following code :
<html>
<head>
<script type="text/javascript">
function validate()
{
fname = f.fn.value;
if(fname!= "abc")
alert("Incorrect name!")
lname = f.ln.value;
if(lname != "xyz")
alert("Incorrect Name!")
paswd = f.pswd.value;
if(paswd<8)
alert("Too short password!")
for(var i=0; i<f.d.length; i++)
{
if(f.d[i].value.checked)
{
document.write(f.d[i].value);
}
}
for(var i=0; i<f.c.length; i++)
{
if(f.c[i].value.checked)
{
alert(f.c[i].value);
}
}
}
</script>
</head>
<body>
<form name="f" onsubmit="validate()">
First Name: <input type = "text" name = "fn"> <br>
Last Name: <input type = "text" name = "ln"> <br>
Password: <input type = "password" name = "pswd"> <br>
E-mail: <input type = "email" name = "mail"> <br>
Degree : <input type = "radio" name = "d" value = 's'> SE
<input type = "radio" name = "d" value = 'c'>CS
<input type = "radio" name = "d" value = 'E'>IT <br>
University
<select name = "uni">
<option value = 'p'>PU</option>
<option value = 'f'>FAST</option>
</select> <br>
CGPA : <input type = "radio" name = "c" value = '3'> >=3.0
<input type = "radio" name = "c" value = '2'> >=2.5 <br>
Browse <input type = "file" name = "uf"> <br>
<input type = "Submit" value = "Submit">
</form>
</body>
</html>
When i press the submit button,I should get a message of
Incorrect name
or
too short password
if the conditions are true but nothing happens, why?
Why the
validate()
function not running?
The Problem
int i
makes no sense. This would be proper Java syntax, but not in Javascript. I think you mean var i
What else?
You have two form tags.
PS
If you're too lazy to open your web browser's console (or if it doesn't have one), just use the try and catch expressions.
I'm too lazy to fix all these issues. Just give me the fixed code
DEMO
First of all:
Just use form once:
<form> // <--- remove this line
<form name="f" onsubmit="validate()">
Second, you're using a mixture of what seems like JAVA and JavaScript, so instead of for(int i, declare your variable with var. Like so:
for (var i = 0; i < f.d.length; i++) { <--- var instead of int
if (f.d[i].value.checked) {
alert(f.d[i].value);
}
}
That should remove all the errors, you could have also seen these errors yourself when using the correct debugging tools. Here is a list of them:
Chrome DevTools: https://developers.google.com/chrome-developer-tools/docs/console
Firebug: http://getfirebug.com/
For Internet Explorer: http://msdn.microsoft.com/en-us/library/ie/dn255006(v=vs.85).aspx
Couple of error in your code
<html>
<head>
<script type="text/javascript">
function validate()
{
fname = document.f.fn.value;
if(fname!= "abc")
alert("Incorrect name!");
lname = f.ln.value;
if(lname != "xyz");
alert("Incorrect Name!");
paswd = f.pswd.value;
if(paswd<8)
alert("Too short password!")
for(i=0; i<f.d.length; i++)
{
if(f.d[i].value.checked)
{
document.write(f.d[i].value);
}
}
for(i=0; i<f.c.length; i++)
{
if(f.c[i].value.checked)
{
alert(f.c[i].value);
}
}
// return false; // use this you don't want to submit form
// return true; //for advancing the form
}
</script>
</head>
<body>
<form action="" name="f" onsubmit=" return validate()">
First Name: <input type = "text" name = "fn"> <br>
Last Name: <input type = "text" name = "ln"> <br>
Password: <input type = "password" name = "pswd"> <br>
E-mail: <input type = "email" name = "mail"> <br>
Degree : <input type = "radio" name = "d" value = 's'> SE
<input type = "radio" name = "d" value = 'c'>CS
<input type = "radio" name = "d" value = 'E'>IT <br>
University <select name = "uni">
<option value = 'p'>PU</option>
<option value = 'f'>FAST</option>
</select> <br>
CGPA : <input type = "radio" name = "c" value = '3'> >=3.0
<input type = "radio" name = "c" value = '2'> >=2.5 <br>
Browse <input type = "file" name = "uf"> <br>
<input type = "submit" value = "Submit">
</form>
</body>
</html>
above code is working
I consider that you are performing validation on this form hence you need to the call the function
return validate();
Now if function return false, the form is not submitted
if function return true, the form is submitted
Do ask for further help , Don't waste my effort's