I am having an issue with the following code:
If you run the following code you get a form with 3 fields: Student ID, Course ID and e-mail. Using javascript i have to check if the student field has 7 characters with two first beeing CS followed by 5 digits. I have to do the same check with the Course ID field but for 5 characters starting with CL followed by 3 digits. The Student ID check works fine but the Course ID does not. From what i see i dont have a mistake ? Thanks in advance.
<!DOCTYPE html>
<html>
<head>
<script>
function validateForm() {
var name = document.forms["mainForm"]["id"].value;
if(name.length != 7) {
alert("Student ID field must be 7 characters");
return false;
}
var csRegex = name.match(/\bCS/);
if(csRegex != "CS") {
alert("Student ID must start with CS prefix");
return false;
}
var digitsRegex = name.match(/[0-9]/g);
if(digitsRegex.length != 5) {
alert("Student ID must start with CS prefix followed by 5 digits");
return false;
}
var courseVar = document.forms["mainForm"]["course"].value;
if(courseVar.length != 5) {
alert("Course ID must be 5 characters");
return false;
}
var clRegex = courseVar.match(/\bCL/);
if(clRegex != "CL") {
alert("Course id must start with CL prefix");
return false;
}
var digitsCourseRegex = courseVar.match(/[0-9]/b);
if(digitsCourseRegex.length != 5) {
alert("Course ID must have 3 digits after CL");
return false;
}
}
</script>
</head>
<body>
<form name="mainForm" onsubmit="return validateForm()">
Student ID:<br>
<input type="text" name="id" maxlength="7" required>
<br>
Course ID:<br>
<input type="text" name="course" maxlength="5" required>
<br>
E-mail:<br>
<input type="email" name="mail" required>
<br><br>
<input type="submit" value="Register">
<input type="reset" value="Reset">
</form>
</body>
</html>
The JS solution is to use a better regular expression to validate the entire string at once:
"CS23444".match(/CS\d{5}/)
adeneo's answer is correct and may be the better actual solution - except it doesn't use JS, it uses HTML5. If he posts an answer that you are OK with, I'd accept that one!
Should var digitsCourseRegex = courseVar.match(/[0-9]/b); be var digitsCourseRegex = courseVar.match(/[0-9]/g);, With the difference being the /b); or the /g);?
Related
My form is validating the two java functions script and if both are true it will continue the form submit. But when i submit it validates only first function validateFormROLLNO() not the second function. Also, when the first function fails it submits the form anyway. I want to submit the form only when the two functions are passed.
first function will check if the roll no = 12 characters.
second function checks if the name is not null.
<body>
<center>
<script type="text/javascript">
function validateFormROLLNO() {
var x = document.forms["myForm"]["id"].value;
if (x !=12) {
alert("ROLLNO must be 12 characters long!!!!");
return false;
}
document.forms["myForm"]["submit"].disabled = true;
document.forms["myForm"]["submit"].value="Wait..";
}
function validateFormNAME() {
var p = document.forms["myForm"]["student"].value;
if (p =='') {
alert("Name cannot be NULL!!!!");
return false;
}
document.forms["myForm"]["submit"].disabled = true;
document.forms["myForm"]["submit"].value="Wait..";
}
function validate(){
return validateFormROLLNO() && validateFormNAME();
}
</script>
<br> <FORM name="myForm" ACTION="insert.jsp" onsubmit="return validate()" METHOD="POST">
Please enter the Rollno and Name you want to INSERT:
<BR> <br>
<b>ISIN :<INPUT TYPE="TEXT" NAME="id"></b>
<BR><BR>
<b> SOURCE :<INPUT TYPE="TEXT" NAME="student"></b>
<br><BR>
<INPUT TYPE="SUBMIT" value="Submit">
</FORM>
</center>
</body>
</html>
There might be some javascript errors exists on the page, that don't let second function to execute. Please use browser's inspect element to explore it.
document.forms["myForm"]["id"].value you are are checking value of the textbox. Please document.forms["myForm"]["id"].value.length to validate it.
Here is the complete method.
function validateFormROLLNO() {
var x = document.forms["myForm"]["id"].value;
if (x.length <12) {
alert("ROLLNO must be 12 characters long!!!!");
return false;
}
else
return true;
document.forms["myForm"]["submit"].disabled = true;
document.forms["myForm"]["submit"].value="Wait..";
}
I have begun learning javascript and I cannot get the security code part of my form (and I have yet to fix the other things such as card number) to bring up an alert if they have not entered 3 integers, I can get it to alert if the person doesnt enter 3 ints/strings/symbols etc... but > or < 3. However I cannot get it to alert the user if the things they pass are not integers. Thank you!.
edit: so the issue im trying to solve is how to run my is_int function on the theForm.cvs.value im sorry if im unclear its all a bit messy.
<script type="text/JavaScript">
function is_int(value){
if((parseFloat(value) == parseInt(value)) && !isNaN(value)){
return true;
} else {
return false;
}
};
function verification(theForm) {
content = "";
var cardLen = (theForm.cardLength.value).length;
var securitycode = new is_int(theForm.cvs.value);
if (cardLen !== 16) {
content += "Please make sure you've entered 16 digits.";
}
if ((theForm.userName.value).length === 0) {
content += "Please make sure you've entered the correct name.";
}
if ((theForm.month.value) < 1 || theForm.month.value > 12 || theForm.month.value === "" || theForm.month.value === "MM") {
content += "Please make sure the you've entered the correct month.";
}
if ((theForm.year.value) < 2016 || ((theForm.year.value) === "" )) {
content += "Please make sure you've entered the correct expiry year.";
}
if ( !securitycode || ( (theForm.cvs.value).length !== 3) ) {
content += "Please make sure you've entered the correct security code.";
}
if (!content == "") {
alert (content); return false;
}
};
</script>
</head>
<body>
<br>
<br>
<br>
<center><h1>Checkout:</h1></center>
<div style="position:absolute; left:600px; top:200px;">
<form name="myForm" class="theForm" onSubmit="return verification(this)" >
Card Number: Expiration:
<br>
<input type="text" name="cardLength"> <input type="text" name="month" style="width:30px" value="MM"> - <input type="text" name="year" style="width:30px" value="YY">
<br>
Name: Security Code:
<br>
<input type="text" name="userName"> <input type="text" name="cvs" style="width:30px">
<br>
<br>
<input type="submit" value="Submit">
</form>
</div>
You don't want to create a new is_int. New creates an instance of an object and calls its constructor, but you just need to get a return value from a function.
if ( !is_int(theForm.cvs.value) || theForm.cvs.value.length !== 3 ) {
content += "Please make sure you've entered the correct security code.";
}
I've used JavaScript to ensure that the fields on my form are correctly filled out (required fields with correct type of information) and the browser seems to ignore the rules I set and process the information anyway.
HTML
HTML
<form id="course-form" name="courseForm" method="POST" onSubmit="return checkCourse()" action="#">
<label for="courseName">Course Name: </label>
<input type="text" id="course-name" name="courseName" placeholder="Course Name" required/><br/>
<br>
<label for="qualDesc">Description: </label><br/>
<textarea name="qualDesc" class="boxsizingBorder" placehold
<label for="entryReqs">Entry Requirements</label><br>
<textarea name="entryReqs" class="boxsizingBorder" id="entry-reqs" placeholder="Previous Grades Required" required></textarea><br>
<br>
<label for="cost">Cost: £</label>
<input type="text" name="cost" id="courseCost" maxlength="6" size="5" required/><br>
<br>
<input type="submit" value="Add Course" />
</form>
JavaScript(Placed in Head of document)
<script>
function checkCourse()
{
var date = new Date();
var year = (date.getFullYear());
var courseName=document.forms["courseForm"]["courseName"].value;
var courseDesc=document.forms["courseForm"]["qualDesc"].value;
var courseYear=document.forms["courseForm"]["year"].value;
var entryReqs=document.forms["courseForm"]["entryReqs"].value;
var cost=document.forms["courseForm"]["cost"].value;
if(courseName == "")
{
alert("Course name is a required field.");
return false;
}
else if(courseDesc=="")
{
alert("The Course needs a description");
return false;
}
else if(courseYear < year)
{
alert("The academic year for " + courseYear + " has already commenced. \n Please pick a later date);
return false;
}
else if(entryReqs=="")
{
alert("You must enter some entry requirements");
return false;
}
else if(isNaN(cost) || (cost==""))
{
alert("Cost is not a valid numerical figure");
}
alert("Course added sucessfully!");
return true;
}
</script>
**Note, I've also tried putting the return true section in an else statement like this:
else
{
alert("Course added sucessfully!");
return true;
}
Am I missing something?
Thanks
In the line below, you try to get the value of an input, but your form does not contain an input that is named year. This will cause a Javascript error and subsequently, your validation will be disregarded and the form will continue to submit
var courseYear=document.forms["courseForm"]["year"].value;
A second problem is you don't return false if the cost validation fails (but this is not your root problem).
Also as juvian points out, you are missing a closing quote on the alert below:
alert("The academic year for " + courseYear + " has already commenced. \n Please pick a later date);
I am trying to validate a form using javascript, Here is my code
<script type="text/javascript">
function prevSubmit(){
var oForm = document.forms[0];
var pass1= oForm.elements["passwd"];
var pass2=oForm.elements["repasswd"];
var flag = 1;
if (pass1.value.length>16) {
document.getElementById("passError").innerHTML = "password may atleast 16 chars";
flag = 0;
}
else
document.getElementById("passError").innerHTML = "";
if(pass1.value<=16 && pass1.value!=pass2.value)
{
document.getElementById("passError").innerHTML = "password must be same";
flag = 0;
}
else
document.getElementById("passError").innerHTML = "";
return flag;
}
</script>
and here is my form element,
<form id="registration_form" action="registration.php" method="post" onsubmit="return prevSubmit();">
<p>
<label>Name</label>
<input type="text" name="name"/>
<span id="NameError"></span>
</p>
<p>
<label>Email</label>
<input type="text" name="email"/>
<span id="emailError"></span>
</p>
<p>
<label>Password</label>
<input type="password" name="passwd"/>
<span id="passError"></span>
</p>
<p>
<label>Repeat Password</label>
<input type="password" name="repasswd"/>
</p>
<input type="submit" class="button" value="sign up"/>
</form>
what I am trying to accomplish is check the password, if no match or greater than 16, then show the message and prevent submission, but its not working, Why?
Use true and false as the values of flag, not 1 and 0. You have to return false to prevent submission, anything else allows submission.
First this error message makes no sense
password may atleast 16 chars
Secondly, your second error check is wrong
if(pass1.value<=16 && pass1.value!=pass2.value)
You are saying if the value is less that the number 16 and the two values do not match.
Why would the value be less that 16? The check should just be
if (pass1.value!=pass2.value)
ANd as the others suggested, use true/false, not 1 and 0 as truthy values.
I agree with answers of Barmar and epascarello.
The if conditions should be implemented in this way:
var oForm = document.forms[0];
var pass1= oForm.elements["passwd"];
var pass2=oForm.elements["repasswd"];
var ctrlError = document.getElementById("passError");
if (pass1.value.length < 16) {
ctrlError.innerHTML = "Password must be at least 16 characters long.";
return false;
}
else if (pass1.value != pass2.value) {
ctrlError.innerHTML = "Passwords do not match.";
return false;
}
else {
ctrlError.innerHTML = "";
return true;
}
just "return false" from javascript method
<input type="submit" class="button" value="sign up" onclick="javascript:return myFunc();"/>
function myFunc()
{
return false;
}
this is basic example of how to prevent submission of form, if we return false then browser/javascript engine prevent further propagation of click event and submission is prevented.
I am validating the dates in below function. If the validation fails, then the form should not get submitted. I tried returning false in form onsubmit but it still gets submitted. However, Validation is working fine and getting the alert that I put in the function. Any help to stop submitting the form if validation fails.
<script>
function dateCheck()
{
start = document.getElementById('name3').value;
end = document.getElementById('name4').value;
compare(start, end);
document.getElementById('name4').focus();
}
function compare(sDate, eDate)
{
function parseDate(input) {
var parts = input.match(/(\d+)/g);
return new Date(parts[2], parts[0]-1, parts[1]); // months are 0-based
}
var parse_sDate = parseDate(sDate);
var parse_eDate = parseDate(eDate);
parse_sDate.setFullYear(parse_sDate.getFullYear() + 1);
if(parse_eDate >= parse_sDate)
{
alert("End date should not be greater than one year from start date");
return false;
}
return true;
}
</script>
</head>
<body>
<form onsubmit="return dateCheck()">
<table>
<tr>
<td><input type="text" name="soname3" id="name3" size="15" readonly="readonly">
<img src="../Image/cal.gif" id="" style="cursor: pointer;" onclick="javascript:NewCssCal('name3','MMddyyyy','dropdown',false,'12')" /></td>
<td><input type="text" name="soname4" id="name4" size="15" readonly="readonly">
<img src="../Image/cal.gif" id="" style="cursor: pointer;" onclick="javascript:NewCssCal('name4','MMddyyyy','dropdown',false,'12'); " /> </td>
</tr>
</table>
<input type="submit" value="Submit">
</form>
Just a comment:
If your listener passes a reference to the form, you can access the controls by name or ID:
<form onsubmit="return dateCheck(this)">
then:
function dateCheck(form) {
var start = form.name3.value;
...
}
Note that you should declare variables, otherwise they will become global at the point they are assigned to. Also, you should check the values in the controls before passing them to the compare function (and display a message asking the user to enter a valid value if they aren't).
function dateCheck(form) {
var start = form.name3.value;
var end = form.name4.value;
var valid = compare(start, end);
if (!valid) form.name4.focus();
return false;
}
I appreciate all contributions above. I have just applied the suggestions above to solve my challenge & it works fine. Keeping it simple I use the following:
<form id="newuser" action="newuser.php" onsubmit="return pswderr(this)">
For the button I have
<input id='submit' type="submit" value="Login" onClick="return pswderr();">
My script is:
<script>
function pswderr() {
var pswd1 = document.getElementById("newuserpswd").value;
var pswd2 = document.getElementById("rptpswd").value;
if (pswd1 !== pswd2) {
document.getElementById("alarm").innerHTML = "Password and password
verification do not match. Retry";
return false;
} else {document.getElementById("alarm").innerHTML = "";
return true;
}
}
</script>
use return on the onclick attribute in the form tag attribute onsubmit="return validateForm()" , if you return false in your validation function in javascript if the input is incorrect then you have to add return to your onclick attribute in order for it to execute .Hope it helped someone!
<script>
function validateForm(){
var validation = false;
var phonenumber = document.forms["enqueryForm"]["phonenumber"].value;
if(phonenumber != 11) {
alert("phonenumber is incorrect");
//e.preventDefault();
return false;
}
}
</script>
<form class="form-style-5" action="BookingForm.php" method="post" id="bookingForm" onsubmit="return validateForm()" name="enqueryForm">
<input type="tel" name="phonenumber" placeholder="your no.">
<input type="submit" name="submit" value="submit">
</form>
return is not going to stop the form from submit if its called in a subfunction e.g. compare(sDate, eDate)
so change your function to this
function dateCheck(e){
var start = document.getElementById('name3').value;
var end = document.getElementById('name4').value;
if(compare(start, end)) {
// no error submit i guess
// return true ?
} else {
// error with date compare
return false;
}
end.focus();
}
In my case i used pattern in input field and also gave maxlength.
What worked with me was, remove Length attribute from input field
you can achieve the same thing using jQuery Form Plugin.
$(document).ready(function() {
$('#your_form_id').ajaxForm( { beforeSubmit: dateCheck } );
});
- I hope this will help you : Just write this code on your Html/jsp page
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
- **Don't forget to add this on your html page**
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type='text/javascript'>
$(document).ready(function() {
//option A
$("regF").submit(function(e) { //regF is form id
alert('submit intercepted');
e.preventDefault(e);
});
});
</script>
</html>