I have a webform in which a user has to fill in details. I am using Javascript and html in order to do multiple input validation with regular expressions. I have part of the javascript + html code below. The variables a-g are regexes of each input field required.
I created an empty Array called Err_arr to stored the errors that has met the conditions (e.g. if the user does not input anything / if the user does not fulfil the required format of input) The error message will be pushed into the array. The last if statement will be used to check whether the array is not empty, hence it will print out all the error messages on multiple lines depending on what the conditions are.
function validateForm() {
var cname = document.getElementById("cname").value;
var odate = document.getElementById("odate").value;
var cno = document.getElementById("cno").value;
var ccn = document.getElementById("ccn").value;
var expm = document.getElementById("expm").value;
var expy = document.getElementById("expy").value;
var cvv = document.getElementById("cvv").value;
var Err_Arr = [];
var a = /^(\w\w+)\s(\w+)$/;
var b = /^(0?[1-9]|[12][0-9]|3[01])[\/\-](0?[1-9]|1[012])[\/\-]\d{4}$/;
var c = /[0-9]{8}/;
var d = /[0-9]{16}/;
var e = /0[0-1]1[0-9]){2}/;
var f = /[0-9]{4}/;
var g = /[0-9]{3}/;
if (cname == null || cname == "") {
Err_Arr.push("Please Enter Info - Customer Name");
}
if (odate == null || odate == "") {
Err_Arr.push("Please Enter Info - Order Date");
}
if (cno == null || cno == "") {
Err_Arr.push("Please Enter Info - Contact No");
}
if (ccn == null || ccn == "") {
Err_Arr.push("Please Enter Info - Credit Card Number");
}
if (expm == null || expm == "") {
Err_Arr.push("Please Enter Info - Expiry Month");
}
if (expy == null || expy == "") {
Err_Arr.push("Please Enter Info - Expiry Year");
}
if (cvv == null || cvv == "") {
Err_Arr.push("Please Enter Info - CVV No");
}
if (cname.test(a) == false) {
Err_Arr.push("Enter correct input");
}
if (odate.test(b) == false) {
Err_Arr.push("Enter correct input");
}
if (cno.test(c) == false) {
Err_Arr.push("Enter correct input");
}
if (ccn.test(d) == false) {
Err_Arr.push("Enter correct input");
}
if (expm.test(e) == false) {
Err_Arr.push("Enter correct input");
}
if (expy.test(f) == false) {
Err_Arr.push("Enter correct input");
}
if (cvv.test(g) == false) {
Err_Arr.push("Enter correct input");
}
if (Err_Arr.length > 0) {
alert(Err_Arr.join("\n"));
}
}
<h2>Part 3 - Javascript with Alert Box</h2>
<form method="get" onsubmit="return validateForm()" name="form1">
Customer name: <input id="cname" type="text" name="cname" autocomplete="off"> <br \> Order date: <input id="odate" type="text" name="odate" autocomplete="off"> <br \> Contact number: (e.g. 98765432) <input id="cno" type="text" name="cno" autocomplete="off"> <br \> Credit card number: (e.g. 123456789) <input id="ccn" type="text" name="ccn" autocomplete="off"> <br \> Expiry date - month part (mm): <input id="expm" type="text" name="expm" autocomplete="off"> <br \> Expiry date - year part (yyyy): <input id="expy"
type="text" name="expy" autocomplete="off"> <br \> CVV Number (e.g. 123): <input id="cvv" type="text" name="cvv" autocomplete="off"> <br \>
<input type="submit" value="Submit">
</form>
I expect the whole web form to give me a whole list of alerts in the conditions that I did not satisfy for the if statements. Instead, my code is not running at all.
The intent of your code is correct. Reason why alerts doesn't show:
A syntax error in var e. notice the missing pair of the parenthesis. should be /0[0-1]1([0-9]){2}/;
.test() is used incorrectly. please refer to w3schools tutorial how to use test. Basically, test() is a method in the Regexp object in javascript. So it should be like regexObject.test(yourString)
Fixing all that most likely will make your code run without issues.
function validateForm() {
var cname = document.getElementById("cname").value;
var Err_Arr = [];
var a = new RegExp(/^(\w\w+)\s(\w+)$/);
if (cname == null || cname == "") {
Err_Arr.push("Please Enter Info - Customer Name");
}
if (!a.test(cname)) {
Err_Arr.push("Enter correct input");
}
if (Err_Arr.length > 0) {
alert(Err_Arr.join("\n"));
}
}
<h2>Part 3 - Javascript with Alert Box</h2>
<form method="get" onsubmit="return validateForm()" name="form1">
Customer name:<input id="cname" type="text" name="cname" autocomplete="off"> <br \>
<input type="submit" value="Submit">
</form>
You have some mistakes:
an invalid regex for e as it has unbalanced parentheses
Strings don't have a test method; regexes do
The suggestion for the credit card number in your HTML would not pass the corresponding regex (that requires 16 digits)
There are also some shorter ways to do things:
if (cname == null || cname == "")
can be just:
if (!cname)
More importantly, you have a lot of code repetition. You could avoid that by doing things in a loop:
function validateForm() {
var validations = [
{ input: "cname", regex: /^(\w\w+)\s(\w+)$/, name: "Customer name" },
{ input: "odate", regex: /^(0?[1-9]|[12]\d|3[01])[\/\-](0?[1-9]|1[012])[\/\-]\d{4}$/, name: "Order date" },
{ input: "cno", regex: /^\d{8}$/, name: "Contact No" },
{ input: "ccn", regex: /^\d{16}$/, name: "Credit Card Number" },
{ input: "expm", regex: /^0?[1-9]|1[012]$/, name: "Expiry Month" }, // Correct regex
{ input: "expy", regex: /^\d{4}$/, name: "Expiry Year" },
{ input: "cvv", regex: /^\d{3}$/, name: "CVV No" }
];
var errors = validations.map(({input, regex, name}) => {
var value = document.getElementById(input).value;
if (!value) return "Please Enter Info - " + name;
if (!regex.test(value)) return "Enter correct input - " + name;
}).filter(Boolean);
if (errors.length) {
alert(errors.join("\n"));
return false;
}
return true;
}
<h2>Part 3 - Javascript with Alert Box</h2>
<form method="get" onsubmit="return validateForm()" name="form1">
Customer name: <input id="cname" type="text" name="cname" autocomplete="off"> <br \>
Order date: <input id="odate" type="text" name="odate" autocomplete="off"> <br \>
Contact number: (e.g. 98765432) <input id="cno" type="text" name="cno" autocomplete="off"> <br \>
Credit card number: (e.g. 1234567890123456) <input id="ccn" type="text" name="ccn" autocomplete="off"> <br \>
Expiry date - month part (mm): <input id="expm" type="text" name="expm" autocomplete="off"> <br \>
Expiry date - year part (yyyy): <input id="expy" type="text" name="expy" autocomplete="off"> <br \>
CVV Number (e.g. 123): <input id="cvv" type="text" name="cvv" autocomplete="off"> <br \>
<input type="submit" value="Submit">
</form>
Related
I have already a form verification in JS, that allows for an alert display in Front when one or several values are incorrect (eg. Password too short, needs at least one number).
I want to change these alerts to messages that will display in an HTML p above the affected input.
I have the following in HTML:
<form id="formNew">
<div>
<p id="msgPseudo"></p>
<label for="pseudo">Pseudo</label>
<br>
<input type="text" name="pseudo" id="pseudo" required>
</div>
<div>
<p id="msgEmail"></p>
<label for="email">Email</label>
<br>
<input type="email" name="email" id="email" minlength="8" maxlength="30" required>
</div>
<div>
<p id="msgPass"></p>
<label for="password">Password</label>
<br>
<input type="password" placeholder="*******" id="password" required>
</div>
<div>
<p id="msgPassRep"></p>
<label for="passwordRepeat">Confirm password</label>
<br>
<input type="password" placeholder="*******" id="confirm_password" required>
</div>
<div>
<input type="submit" name="submit" id="submit" value="Create an account">
</div>
</form>
and the following in JS:
function valideForm(e) {
e.preventDefault();
var valPseudo = document.getElementById("pseudo").value;
var valPassword = document.getElementById("password").value;
var valEmail = document.getElementById("email").value;
var errorsPass = [];
var errorsPseudo = [];
var emailRegex = /.+#.+\..+/;
let letters = 'abcdefghijklmnopqrstuvwxyz'
let numbers = '0123456789'
let letterCount = 0
let numberCount = 0
for (let character of valPseudo.toLowerCase()) {
if (letters.includes(character))
++letterCount
else if (numbers.includes(character))
++numberCount
else
return false //A non [a-zA-Z0-9] character was present
}
if (letterCount + numberCount > 40)
errorsPseudo.push("Pseudo is too long") //The name is too long
if (letterCount + numberCount < 5)
errorsPseudo.push("Pseudo is too short")//The name is too short
if (letterCount < 1)
errorsPseudo.push("Pseudo needs at least one letter") //There aren't enough [a-zA-Z] characters
if (numberCount < 1)
errorsPseudo.push("Pseudo needs at least one number") //There aren't enough [0-9] characters
if (errorsPseudo.length) {
alert(errorsPseudo);
}
if(emailRegex.test(valEmail) == false) {
alert ("veuillez entrer un E-mail valide");
return false;
}
if (!valPassword) {
alert("Password is empty");
}
if((valPassword.length < 8)) {
errorsPass.push("Password should be at least 8 characters")
}
if((valPassword.length > 30)) {
errorsPass.push("Password should not exceed 30 characters")
}
if (!/[A-Z]/.test(valPassword)) {
errorsPass.push("Password should have at least 1 uppercase")
}
if (!/[a-z]/.test(valPassword)) {
errorsPass.push("Password should have at least 1 lowercase")
}
if (!/[0-9]/.test(valPassword)) {
errorsPass.push("Password should have at least 1 number")
}
if (!/(?=.[$#%£&§#])/.test(valPassword)) {
errorsPass.push("Password should have at least 1 special character")
}
if (errorsPass.length) {
alert(errorsPass);
}
var password = document.getElementById("password");
var confirm_password = document.getElementById("confirm_password");
function validatePassword(){
if(password.value != confirm_password.value) {
confirm_password.setCustomValidity("passwords aren't the same");
} else {
confirm_password.setCustomValidity('');
}
}
password.onchange = validatePassword;
confirm_password.onkeyup = validatePassword;
}
document.getElementsByTagName('form')[0].addEventListener('submit', valideForm);
I want to change the alerts display in Pseudo, Email and Password tests, as well as the .setCustomValidity for Password confirmation...
TO messages that will appear in HTML Front at the <p></p> location above each corresponding input.
Is it possible?
You can add a prompt text after the input box, such as the < p > tag. When the input content changes (such as
$("# password"). change (function () {$("P"). text)("messages ")})
)
When a user enters the below link in an input tag, I just want the last part of the string, in order to minimize input mistakes - the two input fields generate a new link that the user can copy and use.
name:id:5icOoE6VgqFKohjWWNp0Ac (I just want the last '5icOoE6VgqFKohjWWNp0Ac' part)
Can anyone help me with amending the below to achieve this?
function generateFullName() {
document.getElementById('txtFullName').value = ('https://nlproducts.nl/item/') + document.getElementById('fName').value + ('?context=') + document.getElementById('lName').value;
}
Enter a product ID:
<input type="text" id="fName" placeholder='0A5gdlrpAuQqZ2iFgnqBFW' />
Enter a user ID:
<input type="text" id="lName" oninput="generateFullName()" placeholder='37i9dQZF1DXcBWIGoYBM5M'/><br/></p>
Tada! This would be the link for your campaign:
<input type="text" id="txtFullName" name="txtFullName" />
Here's a JavaScript function that takes a string as input, and formats it to only keep the last part after the last colon (if it contains a colon):
function parseColon(txt) {
return txt.split(":").slice(-1).pop();
}
Eg. parseColon("a:b:c") would return "c"
You can validate your inputs with:
function isValidInput(txt) {
numberOfColons = txt.split(":").length - 1;
if (txt.length == 32 && numberOfColons == 2)
return true
return false
}
In your code you can use these two functions to check & parse lName and fName like this:
function generateFullName() {
var lName_val = document.getElementById('lName').value;
var fName_val = document.getElementById('fName').value;
//fill in link in the output if fName and lName are valid inputs
if(isValidInput(fName_val) && isValidInput(lName_val))
document.getElementById('txtFullName').value = ('https://nlproducts.nl/item/') + parseColon(fName_val) + ('?context=') + parseColon(lName_val);
// otherwise, clear the output field
else
document.getElementById('txtFullName').value = "";
}
function parseColon(txt) {
// return the part after the last colon
return txt.split(":").slice(-1).pop();
}
function isValidInput(txt) {
numberOfColons = txt.split(":").length - 1;
if (txt.length == 38 && numberOfColons == 2)
return true
return false
}
Enter a product ID:<br>
<input type="text" id="fName" oninput="generateFullName()" placeholder='0A5gdlrpAuQqZ2iFgnqBFW' size="50"/><br/>
Enter a user ID:<br>
<input type="text" id="lName" oninput="generateFullName()" placeholder='37i9dQZF1DXcBWIGoYBM5M' size="50"/><br/><br/>
Tada! This would be the link for your campaign:<br>
<input type="text" id="txtFullName" name="txtFullName" size="50"/>
I have a form that is to add a module to the database, and I have a select field in the form of values 0,1,2,3 ... 0 = invalid and i know i can disable the first field but i don't know if it interferes with the validation process.
Note: rest works fine just when its validating it gets stuck when it gets to the module type (selection)
<?php
include("../authorise.php");
authorise_user("3");
?>
<script src="https://code.jquery.com/jquery-2.2.0.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<body>
<div>
<form id="myForm" method="post">
<label for="module_name">Module Name:</label>
<input name="module_name" id="module_name" type="text" /><br />
<label for="module_code">Module Code:</label>
<input name="module_code" id="module_code" type="text" /><br />
<label for="module_leader">Module Leader:</label>
<input name="module_leader" id="module_leader" type="text" /><br />
<label for="module_type">Module Type:</label>
<select name="module_type" id="module_type">
<option value="0" selected="selected">Please select a module type.</option>
<option value="1">Lecture</option>
<option value="2">Seminar</option>
<option value="3">Lab Practical</option>
</select>
<label for="module_location">Module Location:</label>
<input name="module_location" id="module_location" type="text" /><br />
<label for="module_date">Module Date:</label>
<input name="mnodule_date" id="mnodule_date" type="text" /><br />
<input type="button" id="submitFormData" onclick="SubmitFormData();" value="Submit" />
</form>
</div>
<div id="error"></div>
</body>
<script>
function SubmitFormData() {
var name = $("#module_name").val();
var code = $("#module_code").val();
var leader = $("#module_leader").val();
var type = $("#module_type").val();
var location = $("#module_location").val();
var date = $("#module_date").val();
var validModCode = /[a-zA-Z]{3}\d{6}/
if((name.length < 6)) { 5
var message = "Module Name must be atleast 6 characters.";
$('#error').html(message);
$("#module_name").focus();
return false;
} else if(code == "") {
var message = "Enter a Module Code.";
$('#error').html(message);
$("#module_code").focus();
return false;
} else if(!validModCode.test(code)){
var message = "Invalid Module Code (Format: 3 a-z characters, followed by 6 numeric digits ... e.g. MOD002769).";
$('#error').html(message);
$("#module_code").focus();
return false;
} else if (leader.length < 6) {
var message = "Module leader must be atleast 6 characters.";
$('#error').html(message);
$("#module_leader").focus();
return false;
} else if(type.value == 0) {
var message = "Please choose a Module Type.";
$('#error').html(message);
$("#module_type").focus();
return false;
} else if (location.length < 6) {
var message = "Module location must be atleast 8 characters.";
$('#error').html(message);
$("#module_location").focus();
} else if (date.length < 6) {
var message = "Module date must include a day and a time.";
$('#error').html(message);
$("#module_date").focus();
} else {
$('#error').html("Adding Module");
$.post("addModuleSubmit.php", {
name:name,
code:code,
leader:leader,
type:type,
location:location,
date:date
}, function(data) {
$('#error').html(data);
$('#myForm').trigger('reset');
});
}
}
</script>
Give like this
var type = $("#module_type option:selected").val();
then give check condition like
if(type == 0){ //code }
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.";
}
Here is html code for text field what to check for empty/null values
function myFormValidation() {
alert("HI");
var name = document.getElementById("name").value;
alert(name);
if (name == null || name == " ") {
document.getElementById("inp1").innerHTML = "Enter your name please";
} else {
document.myForm.submit();
}
}
Name
<input type="text" name="name" id="name" />
<input type="hidden" name="inp1" />
<input type="button" value="Register" onclick=" myFormValidation()" />
I want to validate using innerHtml, but my js is not getting called.
I guess removing the space between " " may work
your code
if(name==null || name ==" " ){
document.getElementById("inp1").innerHTML = "Enter your name please";
}
change to
if(name==null || name =="" ){
document.getElementById("inp1").innerHTML = "Enter your name please";
}
You might like to validate the input edit through the help of regular expressions
if ( name == null || /\s*/g.test(name) )
{
document.getElementById("inp1").innerHTML = "Enter your name please";
}
The expression \s* covers both the empty string as well as the input consists of multiple blank spaces, such as " " for example
I'm not really familiar with JavaScript/jQuery but I think this is what you're looking for. I've changed your input for the message to label because your type is hidden which also means that users will not be able to see the message at all.
Also, you didn't include the id attribute for your inp1 so it's impossible to use getElementbyId().
function myFormValidation() {
if (document.getElementById("name").value == "") {
document.getElementById("inp1").innerHTML = "Enter your name please";
}
else {
var name = document.getElementById("name").value;
alert("HI");
alert(name);
document.myForm.submit();
}
}
Name:
<input type="text" name="name" id="name" />
<input type="button" value="Register" onclick=" myFormValidation()" />
<label id="inp1"></label>
Here is example:
function myFormValidation() {
var user = document.getElementById("name").value;
if (user === "") {
document.getElementById("body").innerHTML = "Enter your name please";
} else {
document.getElementById("body").innerHTML = user + " " + "How are you..!";
}
}
Name
<input type="text" name="name" id="name" />
<input type="hidden" />
<input type="button" value="Register" onclick=" myFormValidation()" />
<div id="body"></div>