JavaScript Form HTML - javascript

Evening,
I have to validate a HTML form by pushing it through a Javascript function to make sure no illegal characters are in it. How would I do it for Customer Number and separately for Password but in the same form as they both need to go through to login.jsp
<form onsubmit="return validateNum(this)" action="login.jsp" >
Customer Number: <input type="text" name="customerNumber"/><br/>
Password: <input type="password" name="passphrase"/><br/>
<input type="submit" />
</form>
I am aware that it is completely pointless doing it through Javascript as it can be disabled via the browser and a better way would be through the HTML form its self but that is the parameter that has been set.
I have
function validateNum(fld)
{
var error = "";
var illegalNum = /[\(\)\<\>\,\;\:\\\"\[\]]/[a-z][A-Z];
if (fld.value.length == 0) {
fld.style.background = 'Yellow';
error = "The required field has not been filled in.\n"
}
else if (fld.value == "") {
fld.style.background = 'Yellow';
error = "You didn't enter a Customer Number.\n";
}
else {
fld.style.background = 'White';
}
}
It's half finished as I realized if I put illegal characters A-Z then the password wont work .

Related

JavaScript HTML validation function only works when the form elements are all filled

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;
}

Trying to fix email validation for school project

Hey so uh I have a project due in a few days which requires us to make a contact page where someone can enter a name, email address, subject and message. We need to create javascript to make sure all fields are filled in and that the email is valid.
I have written the HTML for the form, as well as the javascript but I have 2 problems:
No error message displays when no message is entered in the memo field
The email field will not accept a valid email
I have tried to change the ID tag for the email but it automatically allows me to submit straight away without entering any data, I'm quite stuck.
Yes, they are both in two separate documents.
Note: I have not included all the code for the contact page, just the relevant form.
Thank you so much
Here are the images of my code:
HTML for contact page:
Javascript for Contact page:
function checkForm(){
var isValid = true;
var name = document.forms['contact']['name'].value;
var email = document.forms['contact']['emailaddress'].value;
var emailpattern = /\S+#\S+\.\S+/;
var subject = document.forms["contact"]["subject"].value;
var textarea = document.forms["contact"]["memo"].value;
console.log(name, email, subject, textarea);
if(name == ""){
document.getElementById('namemessage').innerHTML = "PLEASE enter a name";
isValid = false;
} else {
document.getElementById('namemessage').style.display = "none";
}
if(!emailpattern.test(emailaddress)){
document.getElementById('emailmessage').innerHTML = "PLEASE enter a valid email";
isValid = false;
}
else {
document.getElementById('emailmessage').style.display = "none";
}
if(subject == ""){
document.getElementById('subjectmessage').innerHTML = "PLEASE enter a subject";
isValid = false;
} else {
document.getElementById('subjectmessage').style.display = "none";
}
if(memo == ""){
document.getElementById('memomessage').innerHTML = "PLEASE enter your request";
isValid = false;
} else {
document.getElementById('memomessage').style.display = "none";
}
return isValid;
}
<main><form action="thankyou.html" name="contact" onsubmit="return checkForm()">
<label for="name">Name:</label>
<input type="text" id="name">
<p id="namemessage"></p><br><br>
<label for="emailaddress">Email Address:</label>
<input type="text" id="emailaddress">
<p id="emailmessage"></p><br><br>
<label for="subject">Subject:</label>
<input type="text" id="subject"><p id="subjectmessage">
</p><br><br>
<label for=memo>Message:</label><br><br>
<textarea id="memo" placeholder = "please type your message here.">
</textarea>
<br><p id="memomessage"></p><br><br>
<input type="submit" value="Submit">
</form>
</main>
No error message displays when no message is entered in the memo field
Because you have:
var textarea = document.forms["contact"]["memo"].value;
...
if (memo == "") {
Change textarea to memo.
The email field will not accept a valid email
Because you have:
var email = document.forms['contact']['emailaddress'].value;
...
if (!emailpattern.test(emailaddress)) {
Change emailaddress to email.
Fix those issues and it "works".

How to make email id in a form optional in JavaScript

I'm creating a form and validating it with JS. I want to make the email id optional. Either i can be left blank or filled. But i want to validate the email id only if the something's typed in the field. And i must use regexe.
"email":{
"regex":"/^([\.a-z0-9_\-]+[#][a-z0-9_\-]+([.][a-z0-9_\-]+)+[a-z]{1,4}$)/i",
"alertText":"* Invalid email address"}
What are the changes should me made here?
You'd have to do a two step validation I think. Apply a different validation check for the email field if its empty.
Since it's Javascript can you do something like:
if (str === '') {
validations['email'] = {}
} else {
validations['email'] = {
// email validation
}
}
I don't know of any other way to do it then that. Maybe there's something you can do with a regex like a condition check but considering how regex work I don't think that it is possible.
Try this
var $email = $('form input[name="email'); //change form to id or containment selector
var re = /[A-Z0-9._%+-]+#[A-Z0-9.-]+.[A-Z]{2,4}/igm;
if ($email.val() != '' && !re.test($email.val()))
{
alert('Please enter a valid email address.');
return false;
}
Try it :
if(email.length > 0) {
//Test Email is Valid Or Not
}
Final code :
<html>
<head>
</head>
<body>
Enter Email : <input type="text" id="txt">
<button onclick="isValid()">Test</button>
<script>
var ele = document.getElementById("txt");
function isValid(){
var email = ele.value;
var patt = /^[a-zA-Z0-9_\-]+#[a-zA-Z0-9_\-]+\.[a-z]{1,4}$/i;
if(email.length > 0) {
if(patt.test(email))
alert("Valid Address Email");
else
alert("Invalid address Email");
}
else
alert("Email is Empty : Valid Address Email");
}
</script>
</body>
</html>
Check links
<input style="margin-top: 20px;" type="text" placeholder="Enter an Email ID" name="Email" id="Email" pattern="((\w+\.)*\w+)#(\w+\.)+(com|kr|net|us|info|biz)" required="required">

Javascript form validation highlight invalid character

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.

How come my JavaScript isn't working?

I am doing a login page for school. I have written the page, but the JavaScript does not seem to work with the form. I have checked over both the form and the JavaScript multiple times, but I see no mistake. Can anyone help me?
function processInfo() {
var theusername;
var thepassword;
theusername = document.myForm.username.value;
thepassword = document.myForm.password.value;
if (document.myForm.username.value = "") {
alert("Please enter in the username.")
return false;
} else if (document.myForm.password = "") {
alert("Please enter in the password.")
return false;
} else if (document.myForm.username.value != "andrew123") {
document.myForm.txtOutput.value = "Incorrect username or password."
} else if (thepassword != "abc") {
document.myForm.txtOutput.value = "Incorrect username or password."
} else if (theusername == "andrew123"
thepassword == "abc") {
document.myForm.txtOutput.value = "Correct! You have successfully logged in."
}
}
<form name="myForm">
<b>User Name:</b>
<input type="text" name="username" size="36" maxlength="100">
<b>Password:</b>
<input type="text" name="password" size="36" maxlength="100">
<p>
<input type=button value="VERIFY INFORMATION" onClick=processInfo()>
</p>
<textarea name="txtOutput" rows=1 cols=4 0></textarea>
</form>
= is an assignment, you keep using it when you are trying to perform a comparison (which would use == or ===).
Sometimes you try to compare the form control with a string instead of getting its .value.
You forgot to put a boolean AND between the two conditions you have theusername == "andrew123"
thepassword == "abc"
You should learn to use the console in your browser as most of these problems would be highlighted in it or could be with the addition of a little logging.

Categories

Resources