i am trying to validate a form with java script .. yet the javascript does not output anything and the form completes into processing.
here is the script tag:
here is the form tag:
<FORM id="frm" name="newCustomer" METHOD="POST" ACTION="register.php" onsubmit="return validateNewCustomer()">
i've created this label so that java script can write the warnings:
<TH WIDTH="30%" NOWRAP> <Label>First Name</Label></TH>
<TD WIDTH="70%"><INPUT TYPE="TEXT" NAME="f_name"
SIZE="8" MAXLENGTH="8">
<label class ="err" id="errname"></label>
Here is the valdiation function :
function validateNewCustomer(){
var name = document.getElementById('f_name').value;
var okCustomer = true;
if(name == ""){
document.getElementById('errname').innerHTML = "Error Name";
okCustomer = okCustomer && false;
}
return okCustomer;
}
I should note that i tried to make the function return false , but it still didn't stop php processing.
I appreciate your help.
Thank you.
var name = document.getElementByName('f_name').value;
and
okCustomer = false; instead of okCustomer = okCustomer && false;
Your code is wrong use
var name = document.getElementsByName('f_name').value;
instead of
var name = document.getElementsById('f_name')[0].value;
Use
if(name.value == ""){
instead of
if(name == ""){
Related
I'm making sign in form with submit. What I want to do is to alert when there is blank in the form. But the function only works when all of the form are filled. Here's the HTML and JS code. The result is the same using onsubmit inside of the HTML or addEventListener("submit" function name)
HTML : It's basically a form for sign in / ordering.
<form id="registration" method="POST" onsubmit="return validate();" action="phplink">
<p> <label for="custName">Name : </label>
<input type="text" id="cname" name="cname" required="required" /> </p>
</form>
JS :
function validate(event) {
event.preventDefault();
var r = document.getElementById("registration");
var cname = r.cname.value;
var errMsg = "";
if (cname == "") {
errMsg += "Please enter your Name.\n";
}
if (errMsg.length != 0) {
alert(errMsg);
result = false;
}
return result;
}
The validation constrains, such as your required="required" are validated before your browser will trigger a submit event. If the validation fails (a value to a required field is not provided) it will not submit your form.
If you want to do the validation using JavaScript instead of the validation constraint attributes, you either need to remove the required="required" attribute (together with any other similar attributes) or you can add the novalidate attribute to your form to indicate that it should not perform this validation on submit.
If you use the latter, you can still use formElement.reportValidity() to see if all the elements satisfy their validation constraints.
If you add a required attribute to each field that shouldn’t be blank, it’ll prevent form submission with empty fields, like this...
<input type="text" name="username" required>
Hi you have several problem. on submit must pass event => onsubmit="return validate(event);" .
you must first defined result and thats your flag => var result = false .
if you want show alert then input dont need required attribute.
so this is your Fixed Code;
function validate(event) {
event.preventDefault();
var result = true;
var r = document.getElementById("registration");
var cname = r.cname.value;
var errMsg = "";
if (cname == "") {
errMsg += "Please enter your Name.\n";
}
if (errMsg.length != 0) {
alert(errMsg);
result = false;
}
return result;
}
I'm just working on some really basic form validation with JS. I don't want users to be able to use any special characters on input fields as a layer of defense against XSS exploits.
I've got the basic validation down and it seems to work ok but it just says there is an error and I would like to highlight the invalid character. here is my code.
HTML
<head><meta charset="UTF-8"><script src="script.js"></script></head>
<body>
<form method="post" action="test.php" onsubmit="return validate()">
<p><input type="text" id="userName" placeholder="Username or Email"></p>
<p><input type="password" id="userEmail" placeholder="Password"></p>
<p><input type="submit" id="submit" value="Login"></p>
</form>
<input type="button" value="debug" onclick="debug()">
<p id="errorText"></p>
<p id="debug"></p>
</body>
Javascript
<script>
function validate() {
var userName = document.getElementById('userName').value;
var userEmail = document.getElementById('userEmail').value;
var invalidChars = "!,#,#,$,%,^,&,*,(,),<,>,/,~,`";
var mergeFields = userName.concat(userEmail);
var found = "false";
var invCharsArr = invalidChars.split(",");
var fieldsArr = mergeFields.split("");
var nameErr = "false";
var emailErr = "false";
for (var i = 0; i < fieldsArr.length; i++) {
if (invCharsArr.indexOf(fieldsArr[i]) > -1) {
found = "true";
break;
}
}
if (found == "true") {
document.getElementById('errorText').innerHTML = "You used an invalid character";
return false;
}
else {
if (userName == "" || userName == null) {
document.getElementById('userName').style.backgroundColor = "red";
document.getElementById('errorText').innerHTML = "Field Errors are Highlighted in Red";
nameErr = "true";
return false;
}
else if (userEmail == "" || userEmail == null) {
document.getElementById('userEmail').style.backgroundColor = "red";
document.getElementById('errorText').innerHTML = "Field Errors are Highlighted in Red";
emailErr = "true";
return false;
}
else {
return true;
}
}
}
</script>
On a side note I am still a beginner with javascript, if there is anything here that I can do better please let me know I would like to learn. Thanks
You can show an error message under the input marking some chars by wrapping them in spans. Doing this on a input field is not possible as far as I know.
<div class="error">Invalid chars in: <span class="mark">#</span>test</div>.
As already mentioned you should not rely on javascript validation only. It mainly helps to prevent sending unnecessary false requests to the server.
Can anyone please help me in doing firstname validation using regex.
In the below javascript code if value.length==0 the error is properly generated.
But even after giving correct firstname format as in regex its throwing error as First name invalid.
I have doubt on my else if block please help me
Java Script code is as below
function validate(){
var valid = true;
var regex="([A-Za-z]{3,30}\s*)";
if (document.getElementById('fname').value.length == 0) {
validationMessage = validationMessage + ' - First name is missing\r\n';
document.getElementById('errorFirstNameMissing').style.visibility='visible';
valid = false;
}
else if(document.getElementById('fname').value!=regex){
validationMessage = validationMessage + ' - First name is not valid can contain
only letters from A-z and a-z\r\n';
document.getElementById('errorFirstNameInValid').style.visibility='visible';
valid = false;
}
else{
document.getElementById('errorFirstNameMissing').style.visibility='hidden';
document.getElementById('errorFirstNameInValid').style.visibility='hidden';
}
if (valid == false){
alert(validationMessage);
}
return valid;
}
and my jsp is code is as below
<form name="Register" action="RegisterServlet" method="post" onSubmit="return validate()">
<table>
<tr>
<td>First Name* : </td>
<td><input type="text" name="txtFname" id="fname" maxlength="30"/><br/>
<span id="errorFirstNameMissing" style="visibility:hidden;">*Please provide your first
name.</span><br/>
<span id="errorFirstNameInValid" style="visibility:hidden;">*Please provide a valid first
name.</span>
</td>
</tr>
regex is not tested like that, you can use:
/^([A-Za-z]{3,30}$)/.test(name)
Read up on the regex object at MDN
I have the following HTML code:
<form name="Register" action="Register.aspx" method="post" runat="server" style="margin-top: 15px;" onsubmit="return validateProfile(FormName='Register');" >
<p> Name* : <input id="FirstName" type="text" name="FirstName"/> </p>
<form>
And this JavaScript code:
function isEmpty(field) {
if (field == "" || field == null)
return false;
}
function validateProfile(FormName) {
var errFname = "";
var Fname = document.forms[FormName]["FirstName"].value;
alert(isEmpty(field=Fname));
return false;
}
The problem here is that the validation doesn't work...
I want that if the field is empty there will be an alert message.
The solution might be very simple, but I just start leran this validtion with javascript.
I have to used the isEmpty function in the code.
change
validateProfile(FormName='Register');
to
validateProfile('Register');
and
alert(isEmpty(field=Fname));
to
alert(isEmpty(Fname));
function validateProfile(FormName) {
var errFname = "";
var Fname = document.forms[FormName]["FirstName"].value;
return isEmpty(Fname);
}
You should use the following code:
function validateProfile(FormName) {
var errFname = "";
var Fname = document.getElementById("FirstName").value;
alert(isEmpty(Fname));
return false;
}
You can use the id of textfield as you have given it.
And change the form tag with code:
<form name="Register" action="Register.aspx" method="post" runat="server" style="margin-top: 15px;" onsubmit="return validateProfile('Register');" >
Javascript does not allow passing function parameters by name
alert(isEmpty(Fname)); // instead of isEmpty(field=Fname)
i'm trying to make sure certain fields are not left blank in my form. it seems simple enough but for some reason it's not working. The alert is not showing, and return false is not working (it continues to post blank entries into my database) please help, what am i doing wrong. thank you!
the script:
function check(){
var name = getElementById('name');
var date = getElementById('date');
var pri = getElementById('pri');
var asapc = getElementById('asapc');
var asapn = getElementById('asapn');
var obr = getElementById('obr');
var obc = getElementById('obc');
var obn = getElementById('obn');
if (name.value == "" || date.value == "" || pri.value == "not" || asapc.value == "" || asapn.value == "" || obr.value == "" || obc.value == "" || obn.value == "") {
alert( "One or more fields were not filled out." );
return false ; }
return true;
}
The code:
<FORM ACTION="step2.php" METHOD="POST" onsubmit="check();">
<!-- fields here -->
<INPUT TYPE="submit" VALUE="CONTINUE">
access every element as document.getElementById... and in form tag write this onsubmit="return check();" instead if onsubmit="check();"
You are missing return here:
<FORM ACTION="step2.php" METHOD="POST" onsubmit="return check();">
You are missing (document) this is the correct syntax:
document.getElementById('id');
<script>
function check() {
var name = document.getElementById('name');
var date = document.getElementById('date');
if (name.value == "" || date.value == "") {
alert( "One or more fields were not filled out.");
return false;
}
}
</script>
and getElementByID means by ID not my tagName
<FORM ACTION="step2.php" METHOD="POST" onsubmit="return check();">
<input name="name" type="text" value="" id="name">
<input name="date" type="text" value="" id="date">
.....etc..
<INPUT TYPE="submit" VALUE="CONTINUE">
</FORM>